然后递归左右子树,因为是递归,使用函数后可认为左右子树已经算出结果,用 left 和 right 表示
如果 left 和 right 都为空,则返回空
若left为空,那最终结果只要看 right
若 right 为空,那最终结果只要看 left
如果 left 和 right 都非空,因为只给了 p 和 q 两个结点,都非空,说明一边一个,因此 root 是他们的最近公共祖先
代码实现
//go /** * Definition for TreeNode. * type TreeNode struct { * Val int * Left *ListNode * Right *ListNode * } */ func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode { // 终止条件 if root == nil { return nil } if root == p || root == q { return root } // 递归 left := lowestCommonAncestor(root.Left, p, q) right := lowestCommonAncestor(root.Right, p, q) // 返回值 if left == nil && right == nil { return nil } if left == nil { return right } if right == nil { return left } return root }
//java 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 null; // 1. if(left == null) return right; // 2. if(right == null) return left; // 3. return root; // 4. if(left != null and right != null) } }