LeetCode之旅(11)

来源:互联网 发布:oper 在js 中什么意思 编辑:程序博客网 时间:2024/05/20 18:48

Binary Tree Preorder Traversal


Given a binary tree, return the preorder traversal of its nodes' values.

For example:
Given binary tree {1,#,2,3},

   1    \     2    /   3

return [1,2,3].

Note: Recursive solution is trivial, could you do it iteratively?


很简单的先序遍历二叉树


/** * Definition for binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    vector<int> preorderTraversal(TreeNode *root) {        vector<int> res;        if (!root) return res;        stack<TreeNode *> s;        s.push(root);        while (!s.empty()) {            TreeNode *t = s.top();            s.pop();            res.push_back(t->val);            if (t->right) s.push(t->right);            if (t->left) s.push(t->left);        }        return res;    }};



0 0
原创粉丝点击