public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root==null||root==q||root==p) return root;
TreeNode left=lowestCommonAncestor(root.left,p,q);
TreeNode right=lowestCommonAncestor(root.right,p,q);
if(left!=null&&right!=null) return root;
else if(left==null&&right!=null) return right;
else if(left!=null&&right==null) return left;
else return null;
}
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root==null) return null;
if(root.val>q.val&&root.val>p.val){
TreeNode left=lowestCommonAncestor(root.left,p,q);
if(left!=null) return left;
}
if(root.val<q.val&&root.val<p.val){
TreeNode right=lowestCommonAncestor(root.right,p,q);
if(right!=null) return right;
}
return root;
}
如果递归函数有返回值,如何区分要搜索一条边,还是搜索整个树呢?
搜索一条边的写法:
if (递归函数(root->left)) return ;
if (递归函数(root->right)) return ;
搜索整个树写法:
left = 递归函数(root->left); // 左
right = 递归函数(root->right); // 右
left与right的逻辑处理; // 中
看出区别了没?
在递归函数有返回值的情况下:如果要搜索一条边,递归函数返回值不为空的时候,立刻返回,如果搜索整个树,直接用一个变量left、right接住返回值,这个left、right后序还有逻辑处理的需要,也就是后序遍历中处理中间节点的逻辑(也是回溯)。
public TreeNode insertIntoBST(TreeNode root, int val) {
if (root == null) {
TreeNode node = new TreeNode(val);
return node;
}
TreeNode cur = root;
TreeNode parent = root; // 这个很重要,需要记录上一个节点,否则无法赋值新节点
while (cur != null) {
parent = cur;
if (cur.val > val) cur = cur.left;
else cur = cur.right;
}
TreeNode node = new TreeNode(val);
if (val < parent.val) parent.left = node;// 此时是用parent节点的进行赋值
else parent.right = node;
return root;
}