每日一题 2019 - 02 - 24
题目:
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:
1 | Input: root = [3,5,1,6,2,0,8,null,null,7,4], target = 5, K = 2 |

Note:
- The given tree is non-empty.
- Each node in the tree has unique values
0 <= node.val <= 500. - The
targetnode is a node in the tree. 0 <= K <= 1000.
解法:
参考网上大佬的做法,如下:
- 我们需要做若干次深度优先遍历。
- 第一次需要定位
target的具体位置,并按顺序记录其到根结点的路径。路径中的每个点,用一个二元组表示,分别为点的指针,和一个布尔值。其中布尔值为true代表target是在当前结点的左侧,否则在右侧。路径不包括target本身。 - 然后,我们顺着路径,从底向上。如果路径上当前的点已经和
target距离为 K,则保存当前结点,然后退出循环。否则,如果布尔值为true,则从右侧开始深度优先遍历找距离target为 K 的结点,否则从左侧开始找。 - 最后,从
target开始深度优先遍历找答案。
代码:
1 | class Solution { |