【binary-tree-preorder-traversal】

来源:互联网 发布:战舰世界雷鸣数据 编辑:程序博客网 时间:2024/06/05 16:19

Given a binary tree, return the preordertraversal 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?


方法一:
非递归实现:
class Solution{public:vector<int> preorderTraversal(TreeNode* root){vector<int> res;if (!root){return res;}stack<TreeNode*> st;st.push(root);while (st.size()){TreeNode* tmp = st.top();st.pop();res.push_back(tmp->val);if (tmp->right){st.push(tmp->right);}if (tmp->left){st.push(tmp->left);}}return res;}};

方法二:
递归实现
class Solution{public:vector<int> preorderTraversal(TreeNode* root){vector<int> ans;LRD(ans, root);return ans;}void LRD(vector<int>&ans, TreeNode* root){if (root==NULL){return;}        ans.push_back(root->val);LRD(ans, root->left);LRD(ans, root->right);}};