标签:
Preorder:
public static void BSTPreorderTraverse(Node node) { if (node == null) { return; } Stack<Node> s = new Stack<Node>(); s.push(node); while (!s.empty()) { node = s.pop(); System.out.println(node.toString()); if (node.rightChild != null) {s.push(node.rightChild);} if (node.leftChild != null) {s.push(node.leftChild);} } }
Inorder:
1 public static void BSTInorderTraverse(Node node) { 2 Stack<Node> s = new Stack<Node>(); 3 while (!s.empty() || node != null) { 4 if (node != null) { 5 s.push(node); 6 node = node.leftChild; 7 } else { 8 node = s.pop(); 9 System.out.println(node.toString()); 10 node = node.rightChild; 11 } 12 } 13 }
Postorder:
1 public List<Integer> postorderTraversal(TreeNode root) { 2 List<Integer> res = new ArrayList<Integer>(); 3 4 if (root == null) { 5 return res; 6 } 7 8 Stack<TreeNode> stack = new Stack<TreeNode>(); 9 stack.push(root); 10 11 while (!stack.isEmpty()) { 12 TreeNode temp = stack.peek(); 13 if (temp.left == null && temp.right == null) { 14 TreeNode pop = stack.pop(); 15 res.add(pop.val); 16 } else { 17 if (temp.right != null) { 18 stack.push(temp.right); 19 temp.right = null; // if we don‘t want to change the tree structure, we can use a set to check whether the node‘s children have been added to the stack or not. 20 } 21 22 if (temp.left != null) { 23 stack.push(temp.left); 24 temp.left = null; 25 } 26 } 27 } 28 29 return res; 30 }
Binary Tree Non-recursive Traversal
标签:
原文地址:http://www.cnblogs.com/beiyeqingteng/p/5743214.html