<Tree> (high frequency) 236

236. Lowest Common Ancestor of a Binary Tree

- if p and q are the left and right subtree, the call to the left and right child nodes recursive function returns the position p and q nodes, respectively, and the current node is precisely what p and q is the smallest common parent node, directly returns to the current node, which is an example of a case where the subject.

- If p and q at the same time in the left subtree, there are two cases, one is left will return p and q in the higher position, and right will return empty, so eventually return to a non-empty left, this is the case in example 2 the title. Another is the minimum return the parent node p and q, the smallest parent node of a node that is currently left sub-tree node is in the p and q, it will be returned.

- if p and q are simultaneously located in the right subtree, likewise there are two cases, one is right will return high p and q at that position, while the left return empty, so the final return of the right to a non-empty , there is a case where a parent node returns the minimum of p and q, the minimum parent node a node that is the right subtree of the current node is p and q are returned

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);
        //left && right return not null
        if(left != null && right != null) return root;
        
        return left == null ? right : left;
    }
}

Guess you like

Origin www.cnblogs.com/Afei-1123/p/12083052.html