码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-08-15 01:28:01      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:

一、前序

 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 }

 

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

标签:

原文地址:http://www.cnblogs.com/deepblueme/p/4731545.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!