[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 }