二叉树的遍历 我的


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;
}
}
}
}

转载于:https://www.cnblogs.com/bockpecehhe/p/9786518.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值