[LeetCode总结]二叉树-前中后序-非递归写法

神评 [★★★★★] 一套带走

作者:sonp orz
链接:https://leetcode-cn.com/problems/binary-tree-postorder-traversal/solution/mo-fang-di-gui-zhi-bian-yi-xing-by-sonp/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

vector<int> preorderTraversal(TreeNode* root) {
    vector<int> res;  //保存结果
    stack<TreeNode*> call;  //调用栈
    if (root != nullptr) call.push(root);  //首先介入root节点
    while (!call.empty()) {
        TreeNode* t = call.top();
        call.pop();  //访问过的节点弹出
        if (t != nullptr) {
            if (t->right) call.push(t->right);  //右节点先压栈,最后处理
            if (t->left) call.push(t->left);
            call.push(t);  //当前节点重新压栈(留着以后处理),因为先序遍历所以最后压栈
            call.push(nullptr);  //在当前节点之前加入一个空节点表示已经访问过了
        }
        else {  //空节点表示之前已经访问过了,现在需要处理除了递归之外的内容
            res.push_back(call.top()->val);  //call.top()是nullptr之前压栈的一个节点,也就是上面call.push(t)中的那个t
            call.pop();  //处理完了,第二次弹出节点(彻底从栈中移除)
        }
    }
    return res;
}

vector<int> inorderTraversal(TreeNode* root) {
    vector<int> res;
    stack<TreeNode*> call;
    if (root != nullptr) call.push(root);
    while (!call.empty()) {
        TreeNode* t = call.top();
        call.pop();
        if (t != nullptr) {
            if (t->right) call.push(t->right);
            call.push(t);  //在左节点之前重新插入该节点,以便在左节点之后处理(访问值)
            call.push(nullptr); //nullptr跟随t插入,标识已经访问过,还没有被处理
            if (t->left) call.push(t->left);
        }
        else {
            res.push_back(call.top()->val);
            call.pop();
        }
    }
    return res;
}

vector<int> postorderTraversal(TreeNode* root) {
    vector<int> res;
    stack<TreeNode*> call;
    if (root != nullptr) call.push(root);
    while (!call.empty()) {
        TreeNode* t = call.top();
        call.pop();
        if (t != nullptr) {
            call.push(t);  //在右节点之前重新插入该节点,以便在最后处理(访问值)
            call.push(nullptr); //nullptr跟随t插入,标识已经访问过,还没有被处理
            if (t->right) call.push(t->right);
            if (t->left) call.push(t->left);
        }
        else {
            res.push_back(call.top()->val);
            call.pop();
        }
    }
    return res;
}

一套带走x2 [★★★★]

https://leetcode.com/problems/binary-tree-postorder-traversal/discuss/45551/Preorder-Inorder-and-Postorder-Iteratively-Summarization

// 英文官网  作者:yavinci
public List<Integer> preorderTraversal(TreeNode root) {
    List<Integer> result = new ArrayList<>();
    Deque<TreeNode> stack = new ArrayDeque<>();
    TreeNode p = root;
    while(!stack.isEmpty() || p != null) {
        if(p != null) {
            stack.push(p);
            result.add(p.val);  // Add before going to children
            p = p.left;
        } else {
            TreeNode node = stack.pop();
            p = node.right;   
        }
    }
    return result;
}

public List<Integer> inorderTraversal(TreeNode root) {
    List<Integer> result = new ArrayList<>();
    Deque<TreeNode> stack = new ArrayDeque<>();
    TreeNode p = root;
    while(!stack.isEmpty() || p != null) {
        if(p != null) {
            stack.push(p);
            p = p.left;
        } else {
            TreeNode node = stack.pop();
            result.add(node.val);  // Add after all left children
            p = node.right;   
        }
    }
    return result;
}

public List<Integer> postorderTraversal(TreeNode root) {
    LinkedList<Integer> result = new LinkedList<>();
    Deque<TreeNode> stack = new ArrayDeque<>();
    TreeNode p = root;
    while(!stack.isEmpty() || p != null) {
        if(p != null) {
            stack.push(p);
            result.addFirst(p.val);  // Reverse the process of preorder
            p = p.right;             // Reverse the process of preorder
        } else {
            TreeNode node = stack.pop();
            p = node.left;           // Reverse the process of preorder
        }
    }
    return result;
}

/* 番外篇
这种模板写法的第三种评论区有些争议,大概是如果这棵树存在类似于拓扑排序的情
况的时候,这个post_order写法会导致最后的结果的顺序可能有问题???(8太懂)评论区也是
看法不一,有人认为有拓扑排序的就不是二叉树了。也有人给出了适用于拓扑排序下
的写法。
*/
// 拓扑排序补充(13赞)  作者:popejoeyxrq   ★★★☆
public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> result=new ArrayList<>();
        Stack<TreeNode> stack=new Stack<>();
        if(root==null){
            return result;
        }
        stack.push(root);
        TreeNode cur=root;
        TreeNode pre=null;
        while (!stack.isEmpty()){
            cur=stack.peek();
            if(cur.left==null&&cur.right==null||(pre!=null&&(pre==cur.left||pre==cur.right))){
                result.add(cur.val); //deal with topological dependency
                stack.pop();
                pre=cur;
            }else {
                if (cur.right!=null){
                    stack.push(cur.right);
                }
                if(cur.left!=null){
                    stack.push(cur.left);
                }
            }
        }
        return result;
}

xiaoyuz666 对yavinci的一些改进 (yavinci评论区)

//   ★★★★
public List<Integer> inorderTraversal(TreeNode root) {
    List<Integer> res = new ArrayList<>();
    if (root == null) return res;

    Stack<TreeNode> stack = new Stack<>();
    TreeNode curr = root;

    while (curr != null || !stack.isEmpty()) {
        while (curr != null) {
            stack.push(curr);
            curr = curr.left;
        }
        curr = stack.pop();
        res.add(curr.val);
        curr = curr.right;
    }
    return res;
}

//preorder  ★★★★★
public List<Integer> preorderTraversal(TreeNode root) {
    List<Integer> list = new ArrayList<>();
    if (root == null) return list;
    Stack<TreeNode> stack = new Stack<>();
    stack.push(root);
    while (!stack.isEmpty()) {
        TreeNode current = stack.pop();
        list.add(current.val);
        if (current.right != null) {
            stack.push(current.right);
        }
        if (current.left != null) {
            stack.push(current.left);
        }
    }
    return list;
}

//postorder ★★★★
public List<Integer> postorderTraversal(TreeNode root) {
    List<Integer> list = new ArrayList<>();
    if (root == null) return list;
    Stack<TreeNode> stack = new Stack<>();
    stack.push(root);
    while (!stack.isEmpty()) {
        TreeNode curr = stack.pop();
        list.add(0, curr.val);
        if (curr.left != null) {
            stack.push(curr.left);
        }
        if (curr.right != null) {
            stack.push(curr.right);
        }
    }
    return list;
}

后序遍历的补充(Iterative solution)这个,,个人感觉有点难不太推荐

// ★★★☆ 好难懂,和下面的那个对照着看吧
// https://leetcode.com/problems/binary-tree-postorder-traversal/discuss/45550/C%2B%2B-Iterative-Recursive-and-Morris-Traversal
vector<int> postorderTraversal(TreeNode* root) {
    vector<int> nodes;
    stack<TreeNode*> todo;
    TreeNode* last = NULL;
    while (root || !todo.empty()) {
        if (root) {
            todo.push(root);
            root = root->left;
        }
        else {
            TreeNode* node = todo.top();
            if (node->right && last != node->right) {
                root = node->right;
            }
            else {
                nodes.push_back(node->val);
                last = node;
                todo.pop();
            }
        }
    }
    return nodes;
}

// ★★★ 这是java的一个,ofLucas,(yavinci评论区)
public List<Integer> postorderTraversal(TreeNode root) {
    Stack<TreeNode> s = new Stack();
    List<Integer> ans = new ArrayList<Integer>();
    TreeNode cur = root;
    while (cur != null || !s.empty()) {
        while (!isLeaf(cur)) {
            s.push(cur);
            cur = cur.left;
        }
        if (cur != null) ans.add(cur.val);
        while (!s.empty() && cur == s.peek().right) {
            cur = s.pop();
            ans.add(cur.val);
        }
        if (s.empty()) cur = null; else cur = s.peek().right;
    }
    return ans;
}

private boolean isLeaf(TreeNode r) {
    if (r == null) return true;
    return r.left == null && r.right == null;
}

测试

暂时写一个想到的树

    1
   / 
  2
 / \
3   4
     \
      5

struct node {
    int v;
    node* l = NULL, * r = NULL;
    node(int x) : v(x){}
};

node* rt = t = new node(1);
t = t->l = new node(2);
t->l = new node(3);
t = t->r = new node(4);
t->r = new node(5);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值