二叉树先序,中序和后序遍历
递归遍历
public void recur(TreeNode root) { // 打印时机
if (root == null) return;
//1 先序
f(root.left);
//2 中序
f(root.right);
//3 后序
}
递归序

每个结点都被访问了三次 得到了下面递归序
ABDDDBEEEBACFFFCGGGCA
- 先序 第一次访问时打印 ABDECFG
- 中序 第二次访问时打印 DBEAFCG
- 后序 第三次访问时打印 DEBFGCA
非递归遍历 左神Ver.
public int[] preOrderTraversal(TreeNode root) {
if(root == null)
return new int[] {};
ArrayList<Integer> array = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while(!stack.isEmpty()) {
root = stack.pop();
array.add(root.val);
if(root.right != null)
stack.push(root.right);
if(root.left != null)
stack.push(root.left);
}
return array.stream().mapToInt(Integer::intValue).toArray();
}
public int[] inOrderTraversal(TreeNode root) {
if(root == null)
return new int[] {};
ArrayList<Integer> array = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
while(!stack.isEmpty() || root != null) {
if(root != null) {
stack.push(root);
root = root.left;
} else {
TreeNode top = stack.pop();
array.add(top.val);
root = top.right;
}
}
return array.stream().mapToInt(Integer::intValue).toArray();
}
public int[] postOrderTraversal(TreeNode root) {
if(root == null)
return new int[] {};
ArrayList<Integer> array = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
Stack<Integer> help = new Stack<>();
stack.push(root);
while(!stack.isEmpty()) {
root = stack.pop();
help.push(root.val);
if(root.left != null)
stack.push(root.left);
if(root.right != null)
stack.push(root.right);
}
while(!help.isEmpty()) {
array.add(help.pop());
}
return array.stream().mapToInt(Integer::intValue).toArray();
}
本文来自博客园,作者:brbrbr,转载请注明原文链接:https://www.cnblogs.com/brbrbr/p/15881483.html

浙公网安备 33010602011771号