1. 程式人生 > >235. Lowest Common Ancestor of a Binary Search Tree

235. Lowest Common Ancestor of a Binary Search Tree

reat system oot main println binary pri HR 實現

原題鏈接:https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/description/
代碼實現:

/**
 * Created by clearbug on 2018/2/26.
 */
public class Solution {

    public static void main(String[] args) {
        Solution s = new Solution();
//        System.out.println(s.lowestCommonAncestor());
    }

    public
TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if (root == null || p == null || q == null) { return null; } if (p.val > q.val) { // just make p.val <= q.val; 這一步可以單獨抽出來,下面的遞歸邏輯單獨寫一個遞歸函數來 TreeNode temp = p; p = q; q = temp; } if
(root.val >= p.val && root.val <= q.val) { return root; } if (root.val > q.val) { return lowestCommonAncestor(root.left, p, q); } if (root.val < p.val) { return lowestCommonAncestor(root.right, p, q); } return
null; } }

235. Lowest Common Ancestor of a Binary Search Tree