zoukankan      html  css  js  c++  java
  • [Leetcode] Binary Tree Postorder Traversal

    Problem statement:

    Thought: Since TreeNode has a self-recursive structure, it's very natural and easy to come up with a recursive implement. But the tricky part is how to implement this using a iterative method. The three binary tree traversal methods: pre-order, in-order and post-order can all be regarded as Depth First Search, and we know the iterative version of DFS makes use of a stack. So maybe we can also use a stack to solve this problem.

    Because this problem is postorder, the relative position of node, left subtree, right subtree should be like this:

    In-order traversal is similar, siwtching position of Right and Node in the above picture.

    Pre-order is the simplest of three, just run iterative-DFS on the root node.

    public class Binary_tree_postorder_traversal {
    
        public ArrayList<Integer> postorderTraversal(TreeNode root) {
            ArrayList<Integer> list = new ArrayList<Integer>();
            if(root == null){
                return list;
            }
            
            Stack<StatusNode> stack = new Stack<StatusNode>();
            stack.push(new StatusNode(root, true));
            stack.push(new StatusNode(root.right, false));
            stack.push(new StatusNode(root.left, false));
            
            while(!stack.isEmpty()){
                StatusNode node = stack.peek();
                if(node.internalNode == null){
                    stack.pop();
                    continue;
                }
                if(node.finished){
                    list.add(stack.pop().internalNode.val);
                    
                }else{
                    stack.push(new StatusNode(node.internalNode.right, false));
                    stack.push(new StatusNode(node.internalNode.left, false));
                    node.finished = true;
                }
            }
            return list;
        }
    
    }
    
    
    class StatusNode{
        boolean finished;// if true, just output it, otherwise expand it
        TreeNode internalNode;
        
        public StatusNode(TreeNode node, boolean finished){
            this.internalNode = node;
            this.finished = finished;
        }
    }
  • 相关阅读:
    【工具类】Stream流构建指定长度的时间集合
    【Java】 Java中的浅拷贝和深拷贝
    【网络协议】 TCP三次握手的流程
    【工具库】Java实体映射工具MapStruct
    【并发编程】Java中的锁有哪些?
    【ORM】Mybatis与JPA的区别
    【并发编程】ThreadLocal
    【SpringBoot】SpringBoot 处理后端返回的小数(全局配置 + 定制化配置)
    实战开发三步走
    项目:jSon和Ajax登录功能
  • 原文地址:https://www.cnblogs.com/Antech/p/3655594.html
Copyright © 2011-2022 走看看