码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 144. Binary Tree Preorder Traversal

时间:2015-01-18 11:45:24      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:

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?

递归方式很简单:

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

对于非递归方式,需要借助堆栈来临时存储tree node

1) if current node P is not empty, visit it and put P->right in stack, then P = P->left

2) else, get the top node in stack

 1 vector<int> preorderTraversal(TreeNode *root) 
 2     {
 3         vector<int> vtree;
 4         stack<TreeNode *> stree;
 5         TreeNode *visit = root;
 6         
 7         while (!stree.empty() || (visit != NULL))
 8         {
 9             if (visit != NULL)  
10             {  
11                 vtree.push_back(visit->val); // if visit is not empty, visit it
12                 if (visit->right != NULL)   // if visit->right exit, push it in stack
13                     stree.push(visit->right);
14                 visit = visit->left;
15             }
16             else    // visit is null
17             {
18                 visit = stree.top();
19                 stree.pop();
20             }
21         }
22         
23         return vtree;
24     }

 

leetcode 144. Binary Tree Preorder Traversal

标签:

原文地址:http://www.cnblogs.com/ym65536/p/4231519.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!