LeetCode题目:1261. 在受污染的二叉树中查找元素

题目

题目连接:https://leetcode-cn.com/problems/find-elements-in-a-contaminated-binary-tree/
题目大意:题目比较简单,看着下面的代码应该可以理解

代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class FindElements {
	//用来存放树的结点值
   public List<Integer> rootlist;
   //构造函数,用来恢复树被污染之前的样子
	public FindElements(TreeNode root) {
		//创建一个存放树结点值的集合
	   rootlist = new ArrayList<Integer>();
	   //将根结点设置为0
		root.val=0;
		//将根结点的值放入集合中
		rootlist.add(root.val);
		//根据题目的提示,如果左子树不为null的话,左子树结点的值为2*根结点的值+1
		if(root.left!=null) {
			root.left = go(root.left,2*root.val+1);
		}
		//根据题目的提示,如果右子树不为null的话,右子树结点的值为2*根结点的值+2
		if(root.right!=null) {
			root.right = go(root.right,2*root.val+2);
		}
		
	}
	//跟上述构造大致相同	    
	private TreeNode go(TreeNode oldroot, int i) {
		TreeNode root = new TreeNode(i);
		rootlist.add(root.val);
		if(oldroot.left!=null) {
			root.left = go(oldroot.left,2*root.val+1);
		}
		if(oldroot.right!=null) {
			root.right = go(oldroot.right,2*root.val+2);
		}
		return root;
	}
	//通过集合查询target值是否在集合中
	public boolean find(int target) {
		if(rootlist.contains(target))
			return true;
		return false;

	}
}

/**
 * Your FindElements object will be instantiated and called as such:
 * FindElements obj = new FindElements(root);
 * boolean param_1 = obj.find(target);
 */
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值