【leetcode刷题笔记】Binary Tree Inorder Traversal

时间:2024-05-02 00:15:45

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还指着一个节点,只有根节点的时候就是这种情况。

代码:

 /**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> inorderTraversal(TreeNode *root) {
vector<int> ans;
stack<TreeNode*>s;
if(root == NULL)
return ans; TreeNode* next = root;
while(!s.empty()||next!=NULL){
if(next != NULL)
{
s.push(next);
next = next->left;
}
else{
next = s.top();
s.pop();
ans.push_back(next->val);
next = next->right; } }
return ans;
}
};