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;
    }

猜你喜欢

转载自www.cnblogs.com/nobodywang/p/10348398.html