• LeetCode145 Binary Tree Postorder Traversal Java题解(递归 迭代)


    题目:

    Given a binary tree, return the postorder traversal of its nodes' values.

    For example:
    Given binary tree {1,#,2,3},

       1
        
         2
        /
       3
    

    return [3,2,1].

    解题:

    递归的还是和前面中序和先序一样。仅仅是交换一下顺序而已

    public static List<Integer> result=new ArrayList<Integer>();
    	 public static List<Integer> postorderTraversal(TreeNode root) {
    		 
    		 if(root!=null)
    		 {
    			 postorderTraversal(root.right);
    			 postorderTraversal(root.left);
    			 result.add(root.val);
    		 }
    		 return result;
    	        
    	    }

    迭代的略微复杂一些  整体上和前面的解法是一样的  只是这边要先訪问左右节点,相同还是以左节点作为主线,只是这里要添加一个栈记录每一个节点的右节点是否已经被訪问过。仅仅有当左右节点都被訪问的前提下才干訪问根节点

    public static List<Integer> postorderTraversal2(TreeNode root) {
    		 
    		 List<Integer> res=new ArrayList<>();
    		 Stack<TreeNode> nodeStack=new Stack<>();
    		 Stack<Integer> nodeState=new Stack<>();//记录右节点是否已经訪问过,1表示已经訪问了,0表示未訪问
    		 
    		 if(root==null)
    			 return res;
    		 else {
    			nodeStack.push(root);
    			nodeState.push(0);
    			root=root.left;
    		}
    		 
    		 while(!nodeStack.isEmpty())
    		 {
    			 while(root!=null)
    			 {
    				 nodeStack.push(root);
    				 nodeState.push(0);
    				 root=root.left;
    			 }//当这个循环跳出的时候  说明nodeStak栈顶的那个节点没有左节点
    			 
    			 if(nodeState.peek()==1)//假设这时候已经訪问过右节点了  这时候就能够訪问根节点
    			 {
    				 res.add(nodeStack.pop().val);
    				 nodeState.pop();//把根节点相应的状态值去除
    				 
    			 }
    			 else {//訪问右节点
    				root=nodeStack.peek().right;
    				nodeState.pop();//更改状态值 由0变1  
    				nodeState.push(1);
    			}
    		 }
    		 return res;
    		
    		
    		
    	        
    	    }


  • 相关阅读:
    ExcelUtil工具类-1
    图论-floyd算法-python实现
    流式编程一些简单的例子
    利用Stream实现简单的等差数列求和
    根据主机IP列表自动部署指定规模的redis cluster
    使用cgroup限制磁盘io读写速率
    consul kv导出和导入(备份)
    mysql8.0 运维相关新特性(未完待续)
    Rider写ASP.NET MVC调试报错
    网络协议知识串讲:搭建一个网络试验环境:授人以鱼不如授人以渔
  • 原文地址:https://www.cnblogs.com/lxjshuju/p/7122092.html
Copyright © 2020-2023  润新知