二叉搜索树和二叉树的最近公共祖先
二叉搜索树的最近公共祖先
1 // 默认p的值小于q的值,需要在输入前调整 2 lowestCommonAncestor(root, p, q) 3 if root.val < p.val and root.val < q.val 4 return lowestCommonAncestor(root.left, p, q) 5 else if root.val > p.val and root.val > q.val 6 return lowestCommonAncestor(root.right, p, q) 7 else 8 return root
二叉树的最近公共祖先
1 lowestCommonAncestor(root, p, q) 2 // 如果root为null,没有找的必要,直接返回null 3 if root = null 4 return null 5 // 如果root为其中一个,表示从root出发找到的最近公共祖先节点有的话只可能是root 6 if root = p or root = q 7 return root 8 9 // 对左子树和右子树递归操作 10 L <- lowestCommonAncestor(root.left, p, q) 11 R <- lowestCommonAncestor(root.right, p, q)) 12 13 // 如果L和R都不为null,表示当前节点就是最近公共祖先节点 14 if L ≠ null and R ≠ null 15 return root 16 else if L = null and R ≠ null 17 return R // 以root节点往下找,如果有目标节点的话只可能是R 18 else if L ≠ null and R = null 19 return L // 以root节点往下找,如果有目标节点的话只可能是L 20 else 21 return null // L和R都为null,都没找到