树的查找和删除节点

查找指定节点

使用我们的前中后序遍历找到一个指定节点,查找HeroNode = 4 分别查找了几次?

例子还是我们上面讲到的那个二叉树,我们先分析

前序查找:先判断当前的no是不是要查找的,是就返回当前节点,不是的话,判断当前节点的左子节点是否为空,若不为空则递归前序查找,找到返回,为空(或者没有找到)的话就去判断右子树,跟我们的左子节点一样

emmmm,其他两种都已一样的套路,这里就不多说了

在这里插入图片描述

前序遍历:小王——>小胡——>小黄——>老肥找到

中序遍历:小胡——>小王——>老肥找到

后序遍历:小胡——>老肥找到

上代码,我用的还是上次的那个二叉树,我直接贴方法的代码,其他的就不补充了

节点中的遍历查找方法

/**
	 * 前序遍历查找
	 * @param no  待查找编号
	 * @return
	 */
	public HeroNode preOrderSearch(int no){
   
		//判断当前节点是不是
		if(this.no == no){
   
			return this;
		}
		//判断左子节点是否为空
		HeroNode resNode = null;//辅助节点
		if(this.left != null){
   
			resNode = this.left.preOrderSearch(no);
		}
		if(resNode != null){
   
			//说明左子树上找到了
			return resNode;
		}
		if(this.right != null){
   
			resNode = this.right.preOrderSearch(no);
		}
		return resNode;
	}
	//中序遍历查找
	public HeroNode infixOrderSearch(int no){
   
		HeroNode resNode = null;
		//先判断当前节点的左子节点
		if(this.left != null){
   
			resNode = this.left.infixOrderSearch(no);
		}
		if(resNode != null){
   
			return resNode;
		}
		if(this.no == no){
   
			return this;
		}
		if(this.right != null){
   
			resNode = this.right.infixOrderSearch(no);
		}
		return resNode;
	}
	//后序遍历查找
	public HeroNode postOrderSearch(int no){
   
		HeroNode resNode = null;
		if(this.left != null){
   
			resNode = this.left.postOrderSearch(no);
		}
		if(resNode != null){
   
			return resNode;
		}
		if(this.right != null){
   
			resNode = this.right.postOrderSearch(no);
		}
		if(resNode != null){
   
			return resNode;
		}
		if(this.no == no)
			return this;
		return resNode;
	}

树中的遍历查找方法

//前序遍历查找 
	public HeroNode preOrderSearch(int no){
   
		if(root != null){
   
			return root.preOrderSearch(no);
		}else{
   
			return null;
		}
	}
	//中序遍历查找 
	public HeroNode infixOrderSearch(int no){
   
		if(root != null){
   
			return root.infixOrderSearch(no);
		}else{
   
			return null;
		}
	}
	//后续序遍历查找 
	public HeroNode postOrderSearch(int no){
   
		if(root != null){
   
			return root.postOrderSearch(no);
		}else{
   
			return null;
		}
	}

测试

		//测试查找
		System.out.println("-----------------------------");
		System.out.println("测试前序遍历查找4号节点");
		System.out.println(binnaryTreeDemo.preOrderSearch(4));
		System.out.println("-----------------------------");
		System.out.println("测试中序遍历查找4号节点");
		System.out.println(binnaryTreeDemo.infixOrderSearch(4));
		System.out.println("-----------------------------");
		System.out.println("测试后序遍历查找4号节点")
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

会写代码的花城

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值