LeetCode Algorithm Binary Tree—LCR 194. The nearest common ancestor of a binary tree

Table of contents

LCR 194. The most recent common ancestor of binary trees - LeetCode

Code:

operation result: 


Given a binary tree, find the nearest common ancestor of two specified nodes in the tree.

The definition of the nearest common ancestor in Baidu Encyclopedia is: "For two nodes p and q of a rooted tree T, the nearest common ancestor is represented as a node x, such that x is the ancestor of p and q and the depth of x is as large as possible ( A node can also be its own ancestor )."

For example, given the following binary tree: root = [3,5,1,6,2,0,8,null,null,7,4]

Example 1:

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
 Output: 3
 Explanation: Node 5 and node 1 ’s nearest common ancestor is node3。

Example 2:

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
 Output: 5
 Explanation: Node 5 and node 4 ’s nearest common ancestor is node 5。because By definition the nearest common ancestor node can be the node itself.

illustrate:

  • All node values ​​are unique.
  • p and q are different nodes and both exist in the given binary tree.

Note: This question is the same as question 236 on the main site: LeetCode official website - the technology growth platform loved by geeks around the world

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) {
        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;
        if(left==null) return right;
        return left;
    }
}

operation result: 

Guess you like

Origin blog.csdn.net/qq_62799214/article/details/133379015