[C++] The front, middle and back order of the binary tree (non-recursive version)

Table of contents

1. Preamble

2. Inorder

 3. Subsequent sequence


 

1. Preamble

Traversing all the way to the left is the root -> left, naturally visit the root first, in line with the order of the preorder, you can directly enter v

 

 vector<int> preorderTraversal(TreeNode* root) {
        // write code here
        vector <int > v;
        stack<TreeNode*> s;
        TreeNode* cur=root;
        while(cur || !s.empty())
        {
            while(cur)
            {
                v.push_back(cur->val);
                s.push(cur);
                cur=cur->left;
            }
            TreeNode* top=s.top();
            s.pop();
            cur=top->right;
        }
        return v;
    }

2. Inorder

You can still visit the root all the way north, but now we need the left

 

vector<int> inorderTraversal(TreeNode* root) {
    vector <int > v;
    stack<TreeNode* > s;
    TreeNode* cur = root;
    while (cur || !s.empty())
    {
        //中序是左 根 右,所以一路向左的时候不能同时把节点保存在v,因为向左都是先访问根,然后走他的左,你连根都不想要为什么全部加到v?
        while (cur)
        {
            s.push(cur);    //保存在栈里,因为这里有根节点,可以帮助找到右子树
            cur = cur->left;
        }
        TreeNode* top = s.top(); //栈顶,左节点/父节点
        s.pop();
        v.push_back(top->val);  //此时的父/左节点就需要加到v
        cur = top->right; //走右
    }
    return v;
}

 3. Subsequent sequence

According to the previous idea, after going all the way to the left, take the top of the stack, but it cannot be accessed directly. It should visit its right subtree and then go to the sub-problem. After walking to the right, come to the root node again. If the right of the root is empty, Directly access the root, if the root is accessed again, also directly access the root

So you need to save the last visited node


   vector<int> postorderTraversal(TreeNode* root) {
        vector <int > v;
        if(!root) return v;
        stack<TreeNode* > s1;
        //s1.push(root);
        TreeNode* cur=root;
        TreeNode* prev=nullptr; //上一个访问的节点
        while(!s1.empty()||cur)
        {
            while(cur)
            {
                s1.push(cur);
                cur=cur->left;
            }
            TreeNode* top=s1.top();
            if(!top->right || top->right==prev)
            {
                s1.pop();
            v.push_back(top->val);
            prev=top;
            }
            else
            cur=top->right;
             
        }
 return v;

        }

Guess you like

Origin blog.csdn.net/weixin_71138261/article/details/129677027