Tuesday, May 17, 2022

[LeetCode] 235. Lowest Common Ancestor of a Binary Search Tree

     

"踏上LeetCode解題之路,順手紀錄一下PHP練功的過程囉。這是第十八篇~~"


Lowest Common Ancestor of a Binary Search Tree - LeetCode

思考過程

待補上


結果

/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     public $val = null;
 *     public $left = null;
 *     public $right = null;
 *     function __construct($value) { $this->val = $value; }
 * }
 */

class Solution {
    /**
     * @param TreeNode $root
     * @param TreeNode $p
     * @param TreeNode $q
     * @return TreeNode
     */
    function lowestCommonAncestor($root, $p, $q) {
        
        if ($root->val == $p->val || $root->val == $q->val) {
            
            return $root;
            
        }elseif ($p->val < $root->val && $q->val < $root->val) {
            
            return $this->lowestCommonAncestor($root->left, $p, $q);
            
        }elseif ($p->val > $root->val && $q->val > $root->val) {
            
            return $this->lowestCommonAncestor($root->right, $p, $q);
            
        }
        return $root;
    }
}

Contact Form

Name

Email *

Message *