Table of contents
236. Recent common ancestor of binary tree
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 A node can also be its own ancestor )."
Example 1:
Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1 Output: 3 Explanation: Node5
and node1
’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: Node5
and node4
’s nearest common ancestor is node5 。
because By definition the nearest common ancestor node can be the node itself.Example 3:
Input: root = [1,2], p = 1, q = 2 Output: 1hint:
- The number of nodes in the tree is
[2, 105]
within the range.-109 <= Node.val <= 109
- All
Node.val
互不相同
.p != q
p
andq
both exist in the given binary tree.
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) { // p=root ,则 q 在 root 的左或右子树中; // q=root ,则 p 在 root 的左或右子树中; // 即题目提示:一个节点也可以是它自己的祖先 if(root==null||root==p||root==q) return root; // 不是则让左右节点继续往下递归,在本层递归看来这步是给left赋值,看看有没有p,q在左子树上 TreeNode left=lowestCommonAncestor(root.left,p,q); // 与上一步一样 TreeNode right=lowestCommonAncestor(root.right,p,q); // 如果left 和 right都不为空,说明此时root就是最近公共节点 // 如果left为空,right不为空,就返回right,说明目标节点是通过right返回的,反之亦然 if(left != null && right != null) return root; if(left==null) return right; return left; } }
operation result: