leetcode 236. Lowest Common Ancestor of a Binary Tree
看看什么是最低共同祖先,就是第一个左右分别存在p和q的节点
还是正常dfs,当遇到null返回null,遇到p返回p,遇到q返回q
若left 和 right 都不为null则说明这就是我们要找的节点
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; return left == null ? right : left; } }