二叉树中所有距离为K的结点
简介
给定一个二叉树(具有根结点 root), 一个目标结点 target ,和一个整数值 K 。
返回到目标结点 target 距离为 K 的所有结点的值的列表。 答案可以以任何顺序返回。
示例 1:
输入:root = [3,5,1,6,2,0,8,null,null,7,4], target = 5, K = 2
输出:[7,4,1]
解释:
所求结点为与目标结点(值为 5)距离为 2 的结点,
值分别为 7,4,以及 1
注意,输入的 “root” 和 “target” 实际上是树上的结点。
上面的输入仅仅是对这些对象进行了序列化描述。来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/all-nodes-distance-k-in-binary-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
class Solution {
Map<TreeNode, String> map = new HashMap<>();//创建map容器,键为节点,值为字符串
String path;
public List<Integer> distanceK(TreeNode node, TreeNode target, int K) {
List<Integer> list = new ArrayList<>();//创建list容器,存放最终筛选出的节点值
getNodeDist(node, target, "");//执行完之后map容器装填完毕
int i;
for (TreeNode key : map.keySet()) {//遍历所有键节点
String s = map.get(key);//get方法返回键对应的值字符串
for (i = 0; i < s.length() && i < path.length() && s.charAt(i) == path.charAt(i); i++) ;
if (s.length() - i + path.length() - i == K)
list.add(key.val);
}
return list;//返回容器
}
void getNodeDist(TreeNode node, TreeNode target, String p) {
if (node != null) {
path = node == target ? p : path;
map.put(node, p);//本方法唯一与外界交流的地方,装填map容器
getNodeDist(node.left, target, p + "0");
getNodeDist(node.right, target, p + "1");
}
}
}
1.递归分析
p与path均为字符串
node=3
target=5
p=""
path=""
----->@1
left: node=5
target=5
p=0
path=0
----->@2
left: node=6
target=5
p=00
path=0
----->@3
left: node=null
end
right: node=null
end
end
right: node=2
target=5
p=01
path=0
----->@4
left: node=7
target=5
p=010
path=0
----->@5
left: node=null
end
right: node=null
end
end
right: node=4
target=5
p=011
path=0
----->@6
left: node=null
end
right: node=null
end
end
end
end
right: node=1
target=5
p=1
path=0
----->@7
left: node=0
target=5
p=10
path=0
----->@8
left: node=null
end
right: node=null
end
end
right: node=8
target=5
p=11
path=0
------>@9
left: node=null
end
right: node=null
end
end
end
end
2.map容器及数据分析
path="0" K=2
K(node) V(p) length i s.length() - i + path.length() - i
@1 3 "" 0 0 0-0+1-0=1
@2 5 "0" 1 1 1-1+1-1=0
@3 6 "00" 2 1 2-1+1-1=1
@4 2 "01" 2 1 2-1+1-1=1
@5 7 "010" 3 1 3-1+1-1=2 add list
@6 4 "011" 3 1 3-1+1-1=2 add list
@7 1 "1" 1 0 1-0+1-0=2 add list
@8 0 "10" 2 0 2-0+1-0=3
@9 8 "11" 2 0 2-0+1-0=3