--- tags: leetcode --- # [1740. Find Distance in a Binary Tree](https://leetcode.com/problems/find-distance-in-a-binary-tree/) --- # My Solution ## The Key Idea for Solving This Coding Question ## C++ Code ```cpp= /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: int findDistance(TreeNode *root, int p, int q) { if (p == q) { return 0; } TreeNode *lca = findLCA(root, p, q); int pLen = 0; if (root->val != p) { pLen = bfs(lca, p); } int qLen = 0; if (root->val != q) { qLen = bfs(lca, q); } return pLen + qLen; } private: TreeNode *findLCA(TreeNode *root, int p, int q) { if (root == nullptr) { return nullptr; } if (root->val == p || root->val == q) { return root; } TreeNode *leftSubtree = findLCA(root->left, p, q); TreeNode *rightSubtree = findLCA(root->right, p, q); if (leftSubtree == nullptr) { return rightSubtree; } if (rightSubtree == nullptr) { return leftSubtree; } return root; } int bfs(TreeNode *root, int val) { if (root == nullptr) { return 0; } int len = 0; queue<TreeNode *> q; q.push(root); while (!q.empty()) { int qLen = q.size(); for (int i = 0; i < qLen; ++i) { TreeNode *curr = q.front(); q.pop(); if (curr->val == val) { return len; } if (curr->left != nullptr) { q.push(curr->left); } if (curr->right != nullptr) { q.push(curr->right); } } ++len; } return -1; } }; ``` ## Time Complexity $O(n)$ $n$ is the number of nodes in the binary tree. ## Space Complexity $O(n)$ $n$ is the number of nodes in the binary tree. # Miscellane <!-- # Test Cases ``` [3,5,1,6,2,0,8,null,null,7,4] 5 0 ``` ``` [3,5,1,6,2,0,8,null,null,7,4] 5 7 ``` ``` [3,5,1,6,2,0,8,null,null,7,4] 5 5 ``` -->