java二叉树的遍历(代码实现)

更新时间:2023-06-30 14:36:57 阅读: 评论:0

java⼆叉树的遍历(代码实现)⼀、前序遍历
访问顺序:先根节点,再左⼦树,最后右⼦树;
1)递归实现
public void preOrderTraver1(TreeNode root) {
if (root != null) {
System.out.print(root.val + "->");
preOrderTraver1(root.left);
preOrderTraver1(root.right);
}
}
2)⾮递归实现
public void preOrderTraver2(TreeNode root) {
Stack<TreeNode> stack = new Stack<>();
TreeNode node = root;
while (node != null || !pty()) {
if (node != null) {
System.out.print(node.val + "->");
stack.push(node);
node = node.left;
} el {
TreeNode tem = stack.pop();
node = tem.right;
}
}
}
⼆、中序遍历
访问顺序:先左⼦树,再根节点,最后右⼦树;
1)递归实现
格兰仕微波炉怎么使用public void inOrderTraver(TreeNode root) {
if (root != null) {
inOrderTraver(root.left);
System.out.print(root.val + "->");
inOrderTraver(root.right);
}
}
2)⾮递归实现
public void inOrderTraver(TreeNode root) {
认知突围
Stack<TreeNode> stack = new Stack<>();
TreeNode node = root;
while (node != null || !stack.isEmpty()) {
if (node != null) {
stack.push(node);
node = node.left;
} el {
TreeNode tem = stack.pop();
System.out.print(tem.val + "->");
node = tem.right;
}
}
}
三、后序遍历
访问顺序:先左⼦树,再右⼦树,最后根节点,上图的访问结果为:AEFDHZMG。1)递归实现
public void postOrderTraver(TreeNode root) {
if (root != null) {
postOrderTraver(root.left);
postOrderTraver(root.right);
System.out.print(root.val + "->");
}
自律用英语怎么说}
2)⾮递归实现
public void postOrderTraver(TreeNode root) {
TreeNode cur, pre = null;
Stack<TreeNode> stack = new Stack<>();
内裤外穿stack.push(root);
while (!pty()) {
cur = stack.peek();
if ((cur.left == null && cur.right == null) || (pre != null && (pre == cur.left || pre == cur.right))) {            System.out.print(cur.val + "->");
stack.pop();生日快乐词
pre = cur;
} el {
if (cur.right != null)
stack.push(cur.right);
if (cur.left != null)
stack.push(cur.left);
}
}
}
四、层次遍历
public void levelOrderTraver(TreeNode root) {
if (root == null) {
return;
}
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(root);
while (!queue.isEmpty()) {
茶壶山TreeNode node = queue.poll();
System.out.print(node.val + "->");
关于生命的句子if (node.left != null) {
queue.add(node.left);
}
if (node.right != null) {
queue.add(node.right);
}
}acwifi
}

本文发布于:2023-06-30 14:36:57,感谢您对本站的认可!

本文链接:https://www.wtabcd.cn/fanwen/fan/82/1070344.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:实现   遍历   访问   递归   节点   顺序   微波炉
相关文章
留言与评论(共有 0 条评论)
   
验证码:
推荐文章
排行榜
Copyright ©2019-2022 Comsenz Inc.Powered by © 专利检索| 网站地图