面試題68 - II.二叉樹的最近公共祖先

面試題68 - II.二叉樹的最近公共祖先

題目描述

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

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

例如,給定如下二叉樹: root = [3,5,1,6,2,0,8,null,null,7,4]
在這裏插入圖片描述

題解

三種情況:
p,q一個在左,一個在右,那麼當前根節點就是最近公共祖先;
p,q都在左;
p,q都在右;
代碼如下:

/**
 * 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) {
        if(root == null) return null;

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

        TreeNode left = lowestCommonAncestor(root.left,p,q);
        TreeNode right = lowestCommonAncestor(root.right,p,q);
//p,q一個在左,一個在右,那麼當前根節點就是最近公共祖先;
        if(left != null && right != null) return root;
//p,q都在左;
        if(left != null) return left;
//p,q都在右;
        if(right != null) return right;

        return null;       
    }
}
提交結果

在這裏插入圖片描述

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