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

Binary Tree Preorder Traversal

时间:2014-08-11 11:53:42      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   color   io   strong   for   ar   

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 class Solution {
 2 public:
 3     vector<int> preorderTraversal( TreeNode *root ) {
 4         vector<int> result;
 5         if( !root ) { return result; }
 6         stack<TreeNode*> nodesStack;
 7         nodesStack.push( root );
 8         while( !nodesStack.empty() ) {
 9             TreeNode* curr = nodesStack.top();
10             nodesStack.pop();
11             result.push_back( curr->val );
12             if( curr->right ) { nodesStack.push( curr->right ); }
13             if( curr->left ) { nodesStack.push( curr->left ); }
14         }
15         return result;
16     }
17 };

 

Binary Tree Preorder Traversal,布布扣,bubuko.com

Binary Tree Preorder Traversal

标签:des   style   blog   color   io   strong   for   ar   

原文地址:http://www.cnblogs.com/moderate-fish/p/3904269.html

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