树的定义
public class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int val) {
this.val = val;
}
}
先序遍历
递归
public static void preOrder(TreeNode root) {
if (root == null) {
return;
}
System.out.println(root.val);
preOrder(root.left);
preOrder(root.right);
}
非递归
public static List<Integer> preOrderWithWhile(TreeNode root) {
List<Integer> list = new ArrayList<>();
Deque<TreeNode> stack = new LinkedList<>();
TreeNode tmp = root;
while (tmp != null || !stack.isEmpty()) {
// 遍历至叶子节点,并将遍历过程中的节点压入栈
while (tmp != null) {
stack.push(tmp);
list.add(tmp.val); // 同时保存遍历过程中的节点
tmp = tmp.left;
}
// 先序遍历 中 左 右
if (!stack.isEmpty()) {
// 将当前节点出栈,同时指针指向其右节点
tmp = stack.pop();
tmp = tmp.right;
}
}
return list;
}
中序遍历
递归
public static void inOrder(TreeNode root) {
if (root == null) {
return;
}
inOrder(root.left);
System.out.println(root.val);
inOrder(root.right);
}
非递归
public static List<Integer> inOrderWithWhile(TreeNode root) {
List<Integer> list = new ArrayList<>();
TreeNode tmp = root;
Deque<TreeNode> stack = new LinkedList<>();
while (tmp != null || !stack.isEmpty()) {
while (tmp != null) {
stack.push(tmp);
tmp = tmp.left;
}
if (!stack.isEmpty()) {
tmp = stack.pop();
list.add(tmp.val);
tmp = tmp.right;
}
}
return list;
}
后序遍历
递归
public static void postOrder(TreeNode root) {
if (root == null) {
return;
}
postOrder(root.left);
postOrder(root.right);
System.out.println(root.val);
}
非递归
public static List<Integer> postOrderWithWhile(TreeNode root) {
Deque<TreeNode> stack = new LinkedList<>();
List<Integer> list = new ArrayList<>();
TreeNode tmp = root;
// 上一个遍历的节点
TreeNode pre = null;
while (tmp != null || !stack.isEmpty()) {
while (tmp != null) {
stack.push(tmp);
tmp = tmp.left;
}
if (!stack.isEmpty()) {
tmp = stack.peek();
if (tmp.right == null || tmp.right == pre) {
stack.pop();
list.add(tmp.val);
pre = tmp;
tmp = null;
} else {
tmp = tmp.right;
}
}
}
return list;
}