美文网首页
二叉树查找的递归终结问题

二叉树查找的递归终结问题

作者: 何几时 | 来源:发表于2020-12-29 09:46 被阅读0次

1. 由labuadong的前中后序套路,修改成java版本

public void threeOrderTraverse(){
   System.out.println("前序遍历");
   if (this.left != null) {
     this.left.threeOrderTraverse();
   }
   System.out.println("中序遍历");
   if (this.right != null) {
     this.right.threeOrderTraverse();
   }
   System.out.println("后序遍历");
}

2. 二叉树的前中后序查找

关键点在于:如何把找到的结点层层返回

以中序查找为例子
Step 1:修改函数名、变量名

class Node{
   int no;
   Node left;
   Node right;
}
public Node inOrderSearch(){
   if (this.left != null) {
     this.left.inOrderSearch();
   }
   System.out.println("中序遍历");
   if (this.right != null) {
     this.right.inOrderSearch();
   }
}

Step 2: 增加业务代码,把参数加进来

public Node inOrderSearch(int no){
   if (this.left != null) {
     this.left.inOrderSearch();
   }
   
   if (this.no == no) {
     return this;
   }   

   if (this.right != null) {
     this.right.inOrderSearch();
   }
}

Step 3: 新建一个接收返回值的变量

public Node inOrderSearch(int no){
   Node resNode = null;
   if (this.left != null) {
     resNode = this.left.inOrderSearch(no);
   }
   
   if (this.no == no) {
     return this;
   }   

   if (this.right != null) {
     resNode = this.right.inOrderSearch(no);
   }
   
   // 如果找不到还是要返回null值
   return resNode;
}

Step 4: 加上一段拦截代码
拦截代码的作用:
若我们找到了结点,则说明返回变量 resNode != null,则可根据以 resNode != null 为条件,接力返回该结点。深层次理解的话,分为找到结点的这层栈的变化,以及没找到结点的其他层栈的变化,这个变化重点在于返回的对象是

  1. 继续递归 -- 中间结点
  2. null -- 叶子结点
  3. this -- 目标结点
  4. resNode -- 接力目标中间变量
public Node inOrderSearch(int no){
   Node resNode = null;
   if (this.left != null) {
     resNode = this.left.inOrderSearch(no);
   }
   // 拦截代码块
   if (resNode != null) {
     return resNode;
   }
  
   if (this.no == no) {
     return this;
   }   

   if (this.right != null) {
     resNode = this.right.inOrderSearch(no);
   }

   // 如果找不到还是要返回null值
   return resNode;
}

相关文章

  • 二叉树查找的递归终结问题

    1. 由labuadong的前中后序套路,修改成java版本 2. 二叉树的前中后序查找 关键点在于:如何把找到的...

  • 2020-10-28

    快排 链表反转 链表反转 二叉树非递归实现 按层排序 二叉树深度 合并有序数组 二分查找 有序数组 查找 楼梯问题

  • 数据结构——树

    有关树的算法题总结 实现二叉树的前序、中序、后序遍历(递归、非递归,mirros方法) 查找后继节点 二叉树的序列...

  • 6. 二叉树创建-查找

    1. 递归方式实现二叉树的构建2. 树、二叉树、二叉查找树3. 二叉树排序树的理解4. 二叉查找树5. 二叉树的查找

  • 二叉树

    来源 二叉树 前序、中序、后序、层次遍历及非递归实现 查找、统计个数、比较、求深度的递归实现 二叉树的实现及先序、...

  • 递归查找的问题

    原文博客地址 背景 前几天在开发过程中遇到一个需求,前端需要动态渲染一个菜单,这个菜单是一个树状结构,就是每个菜单...

  • 算法

    1.算法 链表 二叉树 排序 查找 递归、迭代 位操作 概率 排列组合 1.1 链表 1.1 二叉树 1.3 排序...

  • 平衡二叉树

    查找树 平衡二叉树先是一颗查找树,所以先从查找树的性质讲起。 查找树的递归定义是,每个节点的左孩子值不大于它、右孩...

  • 算法2:递归算法与二分查找

    3.递归算法3.1斐波那契数列(递归)3.2汉诺塔3.3八皇后问题4.⼆分查找递归实现 4.1二分递归查找: 3....

  • 二叉树的遍历递归和非递归

    二叉树的遍历是解决树类问题的关键,二叉树的遍历分为递归和非递归。一般来说,递归的非递归的简单许多,但是一般要求能够...

网友评论

      本文标题:二叉树查找的递归终结问题

      本文链接:https://www.haomeiwen.com/subject/ckexoktx.html