LeetCode-94-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?

算法分析:二叉树中序遍历,非递归方法用栈辅助。

    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> results;
        stack<TreeNode*> stk;
        while(root!=nullptr || !stk.empty()){
            while(root!=nullptr){
                stk.push(root);
                root=root->left;
            }
            TreeNode* temp = stk.top();
            stk.pop();
            results.push_back(temp->val);
            root = temp->right;
        }
        return results;
    }

 

上一篇:力扣——找数左下角的值


下一篇:如何在单个遍历中找到python链表中的中间元素?