leetcode-lowest-common-ancestor-of-a-binary-tree 发表于 2017-02-08 | 分类于 算法 , leetcode | 题目大意 https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/ 二叉树最近邻公共祖先问题 题目分析 利用递归即可 代码12345678910111213141516171819202122232425262728/** * 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是树的节点个数