天天看點

leetcode235-二叉搜尋樹的最近公共祖先二叉搜尋樹的最近公共祖先

文章目錄

  • 二叉搜尋樹的最近公共祖先
    • code

二叉搜尋樹的最近公共祖先

給定一個二叉搜尋樹, 找到該樹中兩個指定節點的最近公共祖先。

百度百科中最近公共祖先的定義為:“對于有根樹 T 的兩個結點 p、q,最近公共祖先表示為一個結點 x,滿足 x 是 p、q 的祖先且 x 的深度盡可能大(一個節點也可以是它自己的祖先)。”

例如,給定如下二叉搜尋樹:  root = [6,2,8,0,4,7,9,null,null,3,5]
           
leetcode235-二叉搜尋樹的最近公共祖先二叉搜尋樹的最近公共祖先

示例 1:

輸入: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
輸出: 6 
解釋: 節點 2 和節點 8 的最近公共祖先是 6。
           

示例 2:

輸入: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4
輸出: 2
解釋: 節點 2 和節點 4 的最近公共祖先是 2, 因為根據定義最近公共祖先節點可以為節點本身。
           

code

思路: 利用二叉搜尋樹的特點,進行遞歸搜尋,根據圖示 分析一遍即可了解
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
            //隻要有一個節點和root節點相同,就直接傳回
            if (root.val == p.val || q.val == root.val) return root;

            //進行比較
            if (root.val > p.val && root.val > q.val) {
                //遞歸向右進行查找
                return lowestCommonAncestor(root.left, p, q);
            } else if (root.val < p.val && root.val < q.val) {
                return lowestCommonAncestor(root.right, p, q);
            } else {
                return root;
            }
        }
}