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

Binary Tree Inorder Traversal

时间:2014-08-18 23:29:53      阅读:254      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   color   使用   io   for   ar   

Given a binary tree, return the inorder traversal of its nodes‘ values.

For example:

Given binary tree {1,#,2,3},

   1
         2
    /
   3

return [1,3,2].

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

思路:使用栈模拟递归过程。以下是网上看到的非常简洁的解法:(若当前节点的左儿子存在,则将左儿子入栈。这样保证了每次从栈顶取出元素时,已经完成了对该元素左子树的访问)

 1 class Solution {
 2 public:
 3     vector<int> inorderTraversal( TreeNode *root ) {
 4         vector<int> values;
 5         stack<TreeNode*> nodeStack;
 6         TreeNode *node = root;
 7         while( !nodeStack.empty() || node ) {
 8             if( node ) {
 9                 nodeStack.push( node );
10                 node = node->left;
11             } else {
12                 node = nodeStack.top();
13                 nodeStack.pop();
14                 values.push_back( node->val );
15                 node = node->right;
16             }
17         }
18         return values;
19     }
20 };

 

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

Binary Tree Inorder Traversal

标签:des   style   blog   color   使用   io   for   ar   

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

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