[94] leetcode preorder binary tree (binary)

Topic links: https://leetcode-cn.com/problems/binary-tree-inorder-traversal/

Title Description

Given a binary tree in preorder to return it.

示例:

输入: [1,null,2,3]
   1
    \
     2
    /
   3

输出: [1,3,2]

Advanced: recursive algorithm is very simple, you can do it through an iterative algorithm?

Thinking

Non-recursive

Stack storage is not accessible right child

class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> ret;
        if(!root) return ret;
        stack<TreeNode *> s;
        TreeNode *last = nullptr;
        while (root  || !s.empty()){
            while (root){
                s.push(root);
                root = root->left;
            }
            if(!s.empty()){
                root = s.top();
                s.pop();
                ret.push_back(root->val);
                root = root->right;
            }
        }
        return ret;
    }
};

Here Insert Picture Description

Guess you like

Origin blog.csdn.net/zjwreal/article/details/91801940