import java.util.Stack;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public class Tree {
//递归先序
public void REPreOrder(TreeNode root) {
if (root == null) return;
System.out.println(root.val);
REPreOrder(root.left);
REPreOrder(root.right);
}
//非递归先序 栈中保存树的右节点
public void PreOrderA(TreeNode root) {
Stack<TreeNode> stack = new Stack<>();
TreeNode p = root;
while (p != null) {
System.out.println(p.val);
if (p.right != null) stack.push(p);
if (p.left != null) p = p.left;
else p = stack.pop();
}
}
//非递归先序 栈中保存树的左子树
public void PreOrderB(TreeNode root) {
Stack<TreeNode> stack = new Stack<>();
while (root != null || !stack.isEmpty()) {
while (root != null) {
stack.push(root);
System.out.println(root.val);
root = root.left;
}
if (!stack.isEmpty()) {
root = stack.pop();
root = root.right;
}
}
}
//递归中序
public void REInOrder(TreeNode root) {
if (root == null) return;
REPreOrder(root.left);
System.out.println(root.val);
REPreOrder(root.right);
}
//非递归中序 栈中保存树的左子树
public void InOrder(TreeNode root) {
Stack<TreeNode> stack = new Stack<>();
while (root != null || !stack.isEmpty()) {
while (root != null) {
stack.push(root);
root = root.left;
}
if (!stack.isEmpty()) {
root = stack.pop();
System.out.println(root.val);
root = root.right;
}
}
}
//递归后序
public void REPostOrder(TreeNode root) {
if (root == null) return;
REPreOrder(root.left);
REPreOrder(root.right);
System.out.println(root.val);
}
//非递归后序 增加标志位栈
/**
* 1. 当root非空时循环:将root和标志1压入栈中,继续遍历左子树
* 2. 当栈非空且栈顶元素的标志位为2,输出该元素
* 3. 当栈非空将栈顶元素的标志位改为2(表示已经为第二次遍历),将root设置为栈顶元素的右子树
* @param root
*/
public void PostOrderA(TreeNode root) {
Stack<TreeNode> stack = new Stack<>();
//标志栈
Stack<Integer> flag = new Stack<>();
while (root != null || !stack.isEmpty()) {
while (root != null) {
stack.push(root);
flag.push(1);
root = root.left;
}
while (!stack.isEmpty() && flag.peek() == 2) {
System.out.println(stack.pop().val);
flag.pop();
}
//第二次遍历到
if (!stack.isEmpty()) {
flag.pop();
flag.push(2);
root = stack.peek().right;
}
}
}
}
前中后序遍历树--递归非递归方法Java实现
最新推荐文章于 2022-04-11 16:55:04 发布