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?
解题:果然不能晚上做题,效率好低。看了讨论才学会的解法。设置一个指针next指向当前访问的节点,如果它不为空,就把它压栈,并且下一个访问它的左节点;如果它为空,就从栈顶一定是它的父节点,取出它的父节点,把这个父节点的值加入向量中,然后去访问父节点的右子。特别注意最后循环结束的条件是栈不空或者next指针不空,因为有可能栈里面的东西弹完了,next还指着一个节点,只有根节点的时候就是这种情况。
代码:
1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 vector<int> inorderTraversal(TreeNode *root) { 13 vector<int> ans; 14 stack<TreeNode*>s; 15 if(root == NULL) 16 return ans; 17 18 TreeNode* next = root; 19 while(!s.empty()||next!=NULL){ 20 if(next != NULL) 21 { 22 s.push(next); 23 next = next->left; 24 } 25 else{ 26 next = s.top(); 27 s.pop(); 28 ans.push_back(next->val); 29 next = next->right; 30 31 } 32 33 } 34 return ans; 35 } 36 };