xinyu04

导航

[Oracle] LeetCode 1740 Find Distance in a Binary Tree

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.

Solution

求树上两个点之间的距离。很经典的做法就是求出 \(LCA\),然后分别求出两点分别到 \(LCA\) 的距离即可

点击查看代码
/**
 * 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 {
private:
    TreeNode* LCA(TreeNode* rt, int p, int q){
        if(!rt) return NULL;
        if(rt->val==p || rt->val==q)return rt;
        TreeNode* leftrt = LCA(rt->left, p,q);
        TreeNode* rightrt = LCA(rt->right, p, q);
        if(leftrt&&rightrt)return rt;
        if(!leftrt && !rightrt)return NULL;
        return leftrt?leftrt:rightrt;
    }
    
    int get_depth(TreeNode* rt, int v, int dep){
        if(!rt) return 0;
        if(rt->val==v) return dep;
        return get_depth(rt->right, v, dep+1)+get_depth(rt->left, v, dep+1);
    }
    
public:
    int findDistance(TreeNode* root, int p, int q) {
        TreeNode* lca = LCA(root, p, q);
        return get_depth(lca,p,0)+get_depth(lca,q,0);
    }
};

posted on 2022-08-19 03:10  Blackzxy  阅读(20)  评论(0编辑  收藏  举报