# All Nodes Distance K in Binary Tree

Mar 07, 2019

• 寻找target节点
• 向下寻找距离当前节点K步的节点
• target节点向前寻找

/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> distanceK(TreeNode* root, TreeNode* target, int K) {
vector<int> res;
if (root == nullptr || target == nullptr) return res;
downSearch(res, target, K);
findTarget(res, root, target, K);
return res;
}

int findTarget(vector<int> &res, TreeNode *root, TreeNode *target, int K) {
if (root == nullptr) return -1;
if (root == target) return K - 1;

// left
int left_k = findTarget(res, root->left, target, K);
if (left_k == 0) {
res.push_back(root->val); return left_k - 1;
} else if (left_k > 0) {
downSearch(res, root->right, left_k-1);
return left_k - 1;
}

int right_k = findTarget(res, root->right, target, K);
if (right_k == 0) {
res.push_back(root->val); return right_k - 1;
} else if (right_k > 0) {
downSearch(res, root->left, right_k-1);
return right_k - 1;
}
return -1;
}

void downSearch(vector<int> &res, TreeNode* p, int K) {
if (p == nullptr || K < 0) return ;
if (K == 0) {
res.push_back(p->val); return;
}
downSearch(res, p->left, K-1);
downSearch(res, p->right, K-1);
}
};

LeetCodeLeetCodeTree

Matchsticks to Square

Sum Root to Leaf Numbers