leetcode-lowest-common-ancestor-of-a-binary-tree

题目大意

  https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/

  二叉树最近邻公共祖先问题

题目分析

  利用递归即可

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null || p == null || q == null) {
return null;
}
if (p == root || q == root) {
return root;
}
TreeNode l = lowestCommonAncestor(root.left, p, q);
TreeNode r = lowestCommonAncestor(root.right, p, q);
if (l != null && r != null) {
return root;
}
if (l == null) {
return r;
}
return l;
}
}

  时间复杂度O(n),n是树的节点个数