All Nodes Distance K in Binary Tree

We are given a binary tree (with root node root), a target node, and an integer value K.

Return a list of the values of all nodes that have a distance K from the target node.  The answer can be returned in any order.

Example 1:

Input: root = [3,5,1,6,2,0,8,null,null,7,4], target = 5, K = 2

Output: [7,4,1]

Explanation: 
The nodes that are a distance 2 from the target node (with value 5)
have values 7, 4, and 1.



Note that the inputs "root" and "target" are actually TreeNodes.
The descriptions of the inputs above are just serializations of these objects.

Note:

  1. The given tree is non-empty.
  2. Each node in the tree has unique values 0 <= node.val <= 500.
  3. The target node is a node in the tree.
  4. 0 <= K <= 1000.

题目理解:

给定一颗二叉树和一个目标节点,找出所有与目标节点距离为K的节点

解题思路:

每一次遍历没有目标节点的子树,直到根节点就是目标节点。具体来说,对于根节点不是目标节点的情况,没有目标节点的子树中的所有节点,都必须经过根节点,然后到达目标节点,因此,可以分别算目标节点到根节点的距离dis1和当前节点到根节点的距离dis2,如果dis1+dis2=K,那么当前节点就是要找的节点。然后递归处理含有根节点的子树

代码如下:

class Solution {
	Set<TreeNode> set;
	List<Integer> list;
	int targetDept, k, v;
    public List<Integer> distanceK(TreeNode root, TreeNode target, int K) {
        set = new HashSet<TreeNode>();
        targetDept = 0;
        findTarget(root, target, 0);
        list = new ArrayList<Integer>();
        k = K;
        v = target.val;
        for(TreeNode it : set) {
        	int layer = it.val / 1000;
        	if(targetDept - layer == K)
        		list.add(it.val % 1000);
        	if(!set.contains(it.left))
        		search(it.left, layer);
        	if(!set.contains(it.right))
        		search(it.right, layer);
        }
        return list;
    }
    
    public void search(TreeNode root, int layer) {
    	if(root == null)
    		return;
    	int d = root.val / 1000, curVal = root.val % 1000;
    	if(d - layer + targetDept - layer == k) {
    		if(!list.contains(curVal))
    			list.add(curVal);
    	}
        search(root.left, layer);
    	search(root.right, layer);
    }
    
    public boolean findTarget(TreeNode root, TreeNode target, int dept) {
    	if(root == null)
    		return false;
    	root.val += dept * 1000;
    	boolean flag = false;
    	if(root.val == target.val) {
    		targetDept = dept;
    		flag = true;
    	}
    	flag |= findTarget(root.left, target, dept + 1);
    	flag |= findTarget(root.right, target, dept + 1);
    	if(flag) {
    		set.add(root);
    		return true;
    	}
    	return false;
    }
}

猜你喜欢

转载自blog.csdn.net/m0_37889928/article/details/82788800