Binary Tree Inorder Traversal

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

Example:

Input: [1,null,2,3]
   1
    \
     2
    /
   3

Output: [1,3,2]

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

code

class Solution
{
public:
    vector<int> inorderTraversal(TreeNode* root)
    {
        if(root==nullptr)
            return {};

        vector<int> res;
        stack<TreeNode *> stack;
        TreeNode *tmp=root;
        while(tmp!=nullptr||!stack.empty())
        {
            while(tmp!=nullptr)
            {
                stack.push(tmp);
                tmp=tmp->left;
            }
            if(!stack.empty())
            {
                tmp=stack.top();
                res.emplace_back(tmp->val);
                stack.pop();
                tmp=tmp->right;
            }
        }
        return res;
    }
};

 

上一篇:Binary Tree Inorder Traversal


下一篇:105. Construct Binary Tree from Preorder and Inorder Traversal