一. 递归
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if(root.val < p.val && root.val < q.val) return lowestCommonAncestor(root.right, p, q); if(root.val > p.val && root.val > q.val) return lowestCommonAncestor(root.left, p, q); return root; }
二. 非递归
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { while(root != null) { if(root.val < p.val && root.val < q.val) // p,q 都在 root 的右子树中 root = root.right; // 遍历至右子节点 else if(root.val > p.val && root.val > q.val) // p,q 都在 root 的左子树中 root = root.left; // 遍历至左子节点 else break; } return root; }
标签:lowestCommonAncestor,TreeNode,val,祖先,二叉,搜索,&&,return,root From: https://www.cnblogs.com/shijianchuzhenzhi/p/16810509.html