首页 > 代码库 > [leetcode-94-Binary Tree Inorder Traversal]

[leetcode-94-Binary Tree Inorder Traversal]

Given a binary tree, return the inorder traversal of its nodes‘ values.
For example:
Given binary tree [1,null,2,3],
1
\
2
/
3
return [1,3,2].
Note: Recursive solution is trivial, could you do it iteratively?

vector<int> inorderTraversal(TreeNode* root)
{
    vector<int>result;
    stack<TreeNode*>st;
    while(root != NULL || !st.empty())
    {
        if(root!= NULL)
        {
            st.push(root);
            root = root->left;
        }
        else
        {
            root = st.top();
            result.push_back(root->val);
            st.pop();
            root = root->right;
        }
    }
    return result;
}

 

[leetcode-94-Binary Tree Inorder Traversal]