二叉树:
class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
中序遍历:
递归:
public void printTreeMid(TreeNode root) {
if (root == null) {
return;
}
printTreeMid(root.left);
System.out.println(root.val);
printTreeMid(root.right);
}
或者:
public void printTreeMid(TreeNode root) {
if (root.left != null) {
printTreeMid(root.left);
}
System.out.println(root.val);
if (root.right != null) {
printTreeMid(root.right);
}
}
执行的内容:先打印 left,再打印自己,再打印 right。
- 打印 left 所需内容:left
- 打印自己所需内容:val
- 打印 right 所需内容:right
递归就是在循环执行这三条语句。
递归转非递归需要用到栈,栈内保存这三种数据,在出栈时执行它们。
入栈时,栈是先进后出的,所以让 right 先进,val 再进,left 最后进。
出栈时,如果是 val,就直接打印,如果不是 val,则重复循环。
非递归:
public void printTreeMid2(TreeNode root) {
Deque<Object> stack = new ArrayDeque<>();
stack.add(root);
while (!stack.isEmpty()) {
Object top = stack.pop();
if (top instanceof Integer) {
System.out.println(top);
} else {
TreeNode topNode = (TreeNode) top;
if (topNode.right != null) {
stack.addFirst(topNode.right);
}
stack.addFirst(topNode.val);
if (topNode.left != null) {
stack.addFirst(topNode.left);
}
}
}
}
同理,前序遍历、后序遍历只需将中序遍历的 while 循环中的三条语句的顺序移动即可。
前序遍历:
前序遍历由于出栈的一定是 node.val,可以省略掉 instanceOf 的判断。
// 递归
public void printTreePre(TreeNode root) {
if (root == null) {
return;
}
System.out.println(root.val);
printTreePre(root.left);
printTreePre(root.right);
}
// 非递归
public void printTreePre2(TreeNode root) {
Deque<TreeNode> stack = new ArrayDeque<>();
stack.add(root);
while (!stack.isEmpty()) {
TreeNode topNode = stack.pop();
if (topNode.right != null) {
stack.addFirst(topNode.right);
}
if (topNode.left != null) {
stack.addFirst(topNode.left);
}
System.out.println(topNode.val);
}
}
后序遍历:
// 递归
public void printTreePost(TreeNode root) {
if (root == null) {
return;
}
printTreePost(root.left);
printTreePost(root.right);
System.out.println(root.val);
}
// 非递归
public void printTreePost2(TreeNode root) {
Deque<Object> stack = new ArrayDeque<>();
stack.addFirst(root);
while (!stack.isEmpty()) {
Object top = stack.pop();
if (top instanceof Integer) {
System.out.println(top);
} else {
TreeNode topNode = (TreeNode) top;
stack.addFirst(topNode.val);
if (topNode.right != null) {
stack.addFirst(topNode.right);
}
if (topNode.left != null) {
stack.addFirst(topNode.left);
}
}
}
}

1510

被折叠的 条评论
为什么被折叠?



