标签: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
标签:des style blog color 使用 io for ar
原文地址:http://www.cnblogs.com/moderate-fish/p/3920520.html