【LeetCode 144_二叉樹_遍歷】Binary Tree Preorder Traversal

QingLiXueShi發表於2015-07-09

解法一:非遞迴

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

解法二:遞迴

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

 

相關文章