前序遍历二叉树代码_二叉树遍历、二叉树深度、代码示例,一点课堂(多岸学院)...

二叉树的遍历 ★★★★★TreeNode 节点/ Definition for a binary tree node. /public class TreeNode {int val;TreeNode left;TreeNode right;

TreeNode(int x) {val = x;}}

  1. 递归调用 (深度优先遍历) ★☆☆☆☆
  2. public void preorderTraversal(TreeNode root) {
  3. if (root == null) {
  4. return;
  5. }
  6. // 可调整前、中、后序遍历
  7. System.out.print(root.val);
  8. preorderTraversal(root.left);
  9. preorderTraversal(root.right);
  10. }
  11. 2.1 非递归遍历 - 基于栈 (前序遍历、深度优先遍历) ★★★☆☆(不推荐)
  12. public List preorderTraversalWithStack(TreeNode root) {
 LinkedList output = new LinkedList<>(); // 用于回溯的栈 Stack stack = new Stack<>(); while (root != null || !stack.isEmpty()) { // 访问结点的数据,并且移动到左子结点,直到无左子结点 while (root != null) { output.add(root.val); stack.push(root); // 将当前节点 push 到栈中,方便后续回溯 root = root.left; // 遍历左子结点 } // 回溯,遍历右子结点 if (!stack.isEmpty()) { root = stack.pop().right; } } return output;}2.2非递归遍历 - 基于栈改进版(基于队列的栈模式)(执行时间较上者提升1倍) ★★★★☆public List preorderTraversalWithStack(TreeNode root) { LinkedList output = new LinkedList<>(); // 用于回溯的栈(基于链表实现,不用担心栈的扩容问题) LinkedList stack = new LinkedList<>(); while (root != null || !stack.isEmpty()) { // 访问结点的数据,并且移动到左子结点,直到无左子结点 while (root != null) { output.add(root.val); stack.add(root); // 将当前节点 add 到栈中,方便后续回溯 root = root.left; // 遍历左子结点 } // 回溯,遍历右子结点 if (!stack.isEmpty()) { root = stack.pollLast().right; } } return output;}3. 非递归遍历 - 基于队列 (层次遍历、广度优先遍历、O(n)) ★★★★☆public List levelorderTraversal(TreeNode root) { LinkedList output = new LinkedList<>(); if (root == null) { return output; } Queue queue = new LinkedList<>(); queue.add(root); // 遍历队列 while (!queue.isEmpty()) { // 从队列头部取出一个结点 root = queue.poll(); output.add(root.val); // 将左右子结点放入队列尾部 if (root.left != null) { queue.add(root.left); } if (root.right != null) { queue.add(root.right); } } return output;}4. Morris Traversal(莫里斯遍历、O(n)) ★★★★☆public List morrisTraversal(TreeNode root) { LinkedList output = new LinkedList<>(); TreeNode prev; TreeNode curr = root; while (curr != null) { // 向左子节点遍历 if (curr.left != null) { prev = curr.left; while (prev.right != null && prev.right != curr) { prev = prev.right; } // 右子节点的回溯指针绑定 if (prev.right == null) { prev.right = curr; curr = curr.left; } else { output.add(curr.val); prev.right = null; curr = curr.right; } // 向右子节点遍历 } else { output.add(curr.val); curr = curr.right; } } return output;}![在这里插入图片描述](https://imgconvert.csdnimg.cn/aHR0cDovL3d3dy55aWRpYW5rdC5jb20vc3RhdGljL2ltZ3Mvd3hnemguanBn?x-oss-process=image/format,png)QQ讨论群组:984370849 706564342 欢迎加入讨论
f16fb8cb321b757dacb628729292dcb3.png

QQ讨论群组:984370849 706564342 欢迎加入讨论

想要深入学习的同学们可以加入QQ群讨论,有全套资源分享,经验探讨,没错,我们等着你,分享互相的故事!

1b8759c868ab958bbe112358bd366197.png
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值