236. Lowest Common Ancestor of a Binary Tree

採用分治法來求解: 

如果找到任意一個node 則返回,這樣就可以分爲三種情況。兩個node 在左右子樹都找到,返回root.

class Solution {

public:

    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {

            if(root == NULL || root == p  || root == q) return root;

             

            //divide

            TreeNode* left = lowestCommonAncestor(root->left, p, q);      

            TreeNode* right = lowestCommonAncestor(root->right, p, q);  

 

            //conquer

            if(left != NULL && right != NULL) return root;

            if(left != NULL) return left;

            else return right;

 

            return NULL;

 

    }

};

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