木落长安rr

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

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

Example:

Input: [1,null,2,3]
   1
    \
     2
    /
   3

Output: [1,2,3]

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

方法一:使用迭代(C++)

 1 vector<int> preorderTraversal(TreeNode* root) {
 2         vector<int> res={};
 3         if(!root)
 4             return res;
 5         stack<TreeNode*> s;
 6         TreeNode* cur=root;
 7         while(!s.empty()||cur){
 8             while(cur){
 9                 res.push_back(cur->val);
10                 s.push(cur);
11                 cur=cur->left;
12             }
13             cur=s.top();
14             s.pop();
15             cur=cur->right;
16         }
17         return res;
18     }

方法二:使用递归,更简单,但是效率较低

 1 void preOrder(TreeNode* root,vector<int>& m){
 2         if(!root)
 3             return;
 4         m.push_back(root->val);
 5         preOrder(root->left,m);
 6         preOrder(root->right,m);
 7     }
 8     
 9     vector<int> preorderTraversal(TreeNode* root) {
10         vector<int> res={};
11         if(!root)
12             return res;
13         preOrder(root,res);
14         return res;
15     }

 

posted on 2019-04-05 16:51  木落长安rr  阅读(209)  评论(0编辑  收藏  举报