二叉树的遍历 我的


private static void preOrder(Node root){
if (root != null){
//先访问根节点 打印 然后左节点 右节点
System.out.print(root.val+"->");
preOrder(root.left);
preOrder(root.right);
}
}

private static void iteratorPreOrder(Node root){
Stack<Node> stack = new Stack<Node>();
stack.push(root);
while (!stack.empty()){
Node cur = stack.pop();
if (cur != null){
System.out.print(cur.val+"->");
stack.push(cur.right);
stack.push(cur.left);
}
}
}

private static void inOder(Node root){
if (root != null){
inOder(root.left);
System.out.print(root.val+"->");
inOder(root.right);
}
}

//left root right 加入的时候按顺序加入 root left 依次弹出 那么为cur = left if(cur.right==null) 继续弹

private static void iteratorInOrder(Node root){
Stack<Node> stack = new Stack<Node>();
Node cur = root;
while (cur != null || !stack.empty()){
while (cur != null){
//把root 和 左节点 加入
stack.push(cur);
cur=cur.left;
}
cur = stack.pop();
System.out.print(cur.val+"->");
cur = cur.right;
}
}

private static void postOrder(Node root){
if (root != null){
preOrder(root.left);
preOrder(root.right);
System.out.println(root.val);
}
}

private static void iteratorPostOrder(Node root){
LinkedList<Integer> arrayList = new LinkedList<Integer>();
Stack<Node> stack = new Stack<Node>();
Node p = root;
while (p != null || !stack.empty()){
if (p != null){
stack.push(p);
arrayList.addFirst(p.val);
p = p.right;
}else {
Node node = stack.pop();
p = node.left;
}
}
}
}

猜你喜欢

转载自www.cnblogs.com/bockpecehhe/p/9786518.html