给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
例如,给定如下二叉搜索树: root = [6,2,8,0,4,7,9,null,null,3,5]
时间复杂度:O(N) 空间复杂度:O(N),最差情况下空间复杂度为数的深度
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if(root == null || root == q || root== p) return root; root.left = lowestCommonAncestor(root.left, p, q); root.right = lowestCommonAncestor(root.right, p, q); if(root.left == null) return root.right; else if(root.right == null) return root.left; else return root; } }时间复杂度:O(N),二叉搜索树的层数最小为logN(满二叉树),最大为N(退化为链表) 空间复杂度:O(1):使用常数大小的额外空间
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { while(root != null){ if(root.val < p.val && root.val < q.val) root = root.right; else if(root.val > p.val && root.val > q.val) root = root.left; else break; } return root; } }