leetcode 236. 二叉樹的最近公共祖先LCA(後序遍歷,回溯)

LCA(Least Common Ancestors),即最近公共祖先,是指在有根樹中,找出某兩個結點u和v最近的公共祖先。node

題目描述

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

百度百科中最近公共祖先的定義爲:「對於有根樹 T 的兩個結點 p、q,最近公共祖先表示爲一個結點 x,知足 x 是 p、q 的祖先且 x 的深度儘量大(一個節點也能夠是它本身的祖先)。」

例如,給定以下二叉樹:  root = [3,5,1,6,2,0,8,null,null,7,4]
示例 1:

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

輸入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
輸出: 5
解釋: 節點 5 和節點 4 的最近公共祖先是節點 5。由於根據定義最近公共祖先節點能夠爲節點自己。
 

說明:

全部節點的值都是惟一的。
p、q 爲不一樣節點且均存在於給定的二叉樹中。

來源:力扣(LeetCode)
連接:https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree
著做權歸領釦網絡全部。商業轉載請聯繫官方受權,非商業轉載請註明出處。

 

遞歸1

 後序遍歷,回溯

  對每一個節點對應的子樹,若該子樹不含有p或q,返回nullptr;不然,若是p和q分別位於當前子樹根節點兩側,則返回當前節點,不然(p和q在同一側,或者只有某一側有p或q)返回來自左邊或右邊的LCA。網絡

/**
 * 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 || root == p || root == q) return root;
        TreeNode left = lowestCommonAncestor(root.left, p, q);
        TreeNode right = lowestCommonAncestor(root.right, p, q);
        if (left!=null && right!=null) return root;
        return left!=null ? left : right;
    }
}

 

遞歸法2

思路spa

二叉樹作後序遍歷,回溯:
    回溯時: 捕獲mid,即當前節點是否爲p或q; 當 left right mid 三個中有兩個爲True時,說明當前節點是最近的公共節點,記錄至res;
    返回值: 左子樹或右子樹或當前節點中包含p或q;
最終,返回最近公共節點res。

class Solution {
    TreeNode res = null;
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        dfs(root, p, q);
        return res;
    }
    private int dfs(TreeNode root, TreeNode p, TreeNode q){
        if(root == null) return 0;
        int left = dfs(root.left, p, q);
        int right = dfs(root.right, p, q);
        int mid = root == p || root == q ? 1 : 0;
        if(left + right + mid > 1) res = root;
        return left + right + mid > 0 ? 1 : 0;
    }
}
相關文章
相關標籤/搜索