[Leetcode] Binary tree travelsal (preorder, inorder, postorder)

一、前序

 1 public List<Node> preOrder(Node root){
 2     List<Node> res = new LinkedList<Node>();
 3     Stack<Node> stack = new Stack<Node>();
 4     stack.push(root);
 5     while(root!=null||!stack.isEmpty()){
 6         while(root){
 7             res.add(root);
 8             stack.push(root);
 9             root=root.left;
10         }
11         Node tmp = stack.pop();
12         root= tmp.right;
13     }
14     return res;
15 }

二、中序

 1 public List<Node> inOrder(Node root){
 2     List<Node> res = new LinkedList<Node>();
 3     Stack<Node> stack = new Stack<Node>();
 4     stack.push(root);
 5     while(root!=null||!stack.isEmpty()){
 6         while(root){
 7             stack.push(root);
 8             root= root.left;
 9         }
10         Node tmp = stack.pop();
11         res.add(tmp);
12         root=tmp.right;
13     }
14 }

三、后序

 1 public List<Node> postOrder(Node root){
 2     List<Node> res = new LinkedList<Node>();
 3     Stack<Node> stack = new Stack<Node>();
 4     stack.push(root);
 5     Node head = root;
 6     while(!stack.isEmpty()){
 7         Node current =stack.peek();//do not know if should pop()
 8         if(current.right==head||current.left==head||(current.left==null||current.right==null)){
 9             stack.pop();
10             res.add(current);
11             head=current;
12         }else{
13             if(current.right!=null) stack.push(current.right);
14             if(current.left!=null) stack.push(current.left);
15         }
16     }
17 }

 

转载于:https://www.cnblogs.com/deepblueme/p/4731545.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值