二叉树
前序遍历
递归
借助栈进行排序
- 先将根节点压栈
- 栈不为空,如果存在根节点,先右后左。
- 弹栈打印。直至栈为空
package com.vitamin.tree;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
/**
* @author
* 2022/4/7 11:06
*/
public class PreOrderTree {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
if (root == null) {
return list;
}
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode pop = stack.pop();
list.add(pop.val);
if (pop.right != null) {
stack.push(pop.right);
}
if (pop.left != null) {
stack.push(pop.left);
}
}
return list;
}
public void preOrder(TreeNode root, int type) {
if (root == null) {
return;
}
System.out.println(root.val);
preOrder(root.left, 1);
preOrder(root.right, 1);
}
}
后序遍历
递归
借助两个栈
-
先押入跟节点到栈A.
-
栈不为空,如果存在根节点,先左后右。
-
弹栈压入栈B.zhan
-
最后的打印顺序是 栈B的出栈顺序
辅助栈B的入栈顺序是 跟右左
代码实现
package com.vitamin.tree;
import com.vitamin.list.ListNode;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
/**
* @author
* 2022/4/7 11:12
*/
public class PostOrderTree {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
if (root == null) {
return list;
}
Stack<TreeNode> stackTemp = new Stack<>();
Stack<TreeNode> stack = new Stack<>();
stackTemp.push(root);
while (!stackTemp.isEmpty()) {
TreeNode pop = stackTemp.pop();
stack.push(pop);
if (pop.left != null) {
stackTemp.push(pop.left);
}
if (pop.right != null) {
stackTemp.push(pop.right);
}
}
while (!stack.isEmpty()) {
TreeNode pop = stack.pop();
list.add(pop.val);
}
return list;
}
}