1. 先序遍历
public void preorder(TreeNode root) { if(root == null) return; Stack<TreeNode> stack = new Stack<TreeNode>(); while(true) { if(root == null) { if(stack.isEmpty()) break; root = stack.pop(); } else { System.out.println(root.val); if(root.right != null) stack.push(root.right); root = root.left; } } }
2. 中序遍历
public void inorder(TreeNode root) { if(root == null) return; Stack<TreeNode> stack = new Stack<TreeNode>(); while(true) { if(root == null) { if(stack.isEmpty()) break; root = stack.pop(); System.out.println(root.val); root = root.right; } else if(root.left != null) { stack.push(root); root = root.left; } else { System.out.println(root.val); root = root.right; } } }
3. 后序遍历, 需要两个栈,其中一个栈用来记录对应节点是否已经访问了它的右节点
public void postorder(TreeNode root) { if(root == null) return; Stack<TreeNode> stack = new Stack<TreeNode>(); Stack<Boolean> flags = new Stack<Boolean>(); while(true) { if(root == null) { if(stack.isEmpty()) { break; } if(flags.peek()) { System.out.println(stack.pop().val); flags.pop(); } else { flags.pop(); flags.push(true); root = stack.peek().right; } } else if(root.left != null) { stack.push(root); flags.push(false); root = root.left; } else if(root.right != null) { stack.push(root); flags.push(true); root = root.right; } else { System.out.println(root.val); root = null; } } }
时间: 2024-10-14 06:26:03