【leetcode】236 二叉樹的最近公共祖先

題目描述:

https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree/

思路: 

代碼實現:

class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if(!root || p == root || q == root)
            return root;
        TreeNode* left = lowestCommonAncestor(root->left,p,q);
        TreeNode* right = lowestCommonAncestor(root->right, p, q);
        if(left && right)
            return root;
        else return left? left:right;
    }
};

 參考:https://www.cnblogs.com/grandyang/p/4641968.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章