Skip to content

Latest commit

 

History

History

1740

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

Given the root of a binary tree and two integers p and q, return the distance between the nodes of value p and value q in the tree.

The distance between two nodes is the number of edges on the path from one to the other.

 

Example 1:

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 0
Output: 3
Explanation: There are 3 edges between 5 and 0: 5-3-1-0.

Example 2:

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 7
Output: 2
Explanation: There are 2 edges between 5 and 7: 5-2-7.

Example 3:

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 5
Output: 0
Explanation: The distance between a node and itself is 0.

 

Constraints:

  • The number of nodes in the tree is in the range [1, 104].
  • 0 <= Node.val <= 109
  • All Node.val are unique.
  • p and q are values in the tree.

Companies:
Amazon, Apple

Related Topics:
Hash Table, Tree, Depth-First Search, Breadth-First Search, Binary Tree

Similar Questions:

Solution 1. Find Path

// OJ: https://leetcode.com/problems/find-distance-in-a-binary-tree/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(H)
class Solution {
    bool findPath(TreeNode *root, int target, vector<TreeNode*> &path) {
        if (!root) return false;
        path.push_back(root);
        if (root->val == target || findPath(root->left, target, path) || findPath(root->right, target, path)) return true;
        path.pop_back();
        return false;
    }
public:
    int findDistance(TreeNode* root, int p, int q) {
        if (p == q) return 0;
        vector<TreeNode*> a, b;
        findPath(root, p, a);
        findPath(root, q, b);
        int i = 0;
        while (i < a.size() && i < b.size() && a[i] == b[i]) ++i;
        return a.size() + b.size() - 2 * i;
    }
};

Solution 2. Post-order Traversal

// OJ: https://leetcode.com/problems/find-distance-in-a-binary-tree/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(H)
class Solution {
    int lcaDepth = 0;
    vector<int> depth;
    TreeNode* dfs(TreeNode *root, int p, int q, int d = 0) {
        if (!root) return nullptr;
        auto left = dfs(root->left, p, q, d + 1), right = dfs(root->right, p, q, d + 1);
        if (root->val == p || root->val == q) {
            depth.push_back(d);
            lcaDepth = d;
            return root;
        }
        if (left && right) lcaDepth = d;
        return left && right ? root : (left ? left : right);
    }
public:
    int findDistance(TreeNode* root, int p, int q) {
        if (p == q) return 0;
        dfs(root, p, q);
        return depth[0] + depth[1] - 2 * lcaDepth;
    }
};