235. 二叉搜索樹的最近公共祖先
題目鏈接:235. 二叉搜索樹的最近公共祖先
第一個(gè)遍歷到的在p和q之間的數(shù)一定是他們的最近公共祖先
迭代法注意return語(yǔ)句的位置
701. 二叉搜索樹中的插入操作
題目鏈接:701. 二叉搜索樹中的插入操作
- 迭代法考慮的情況多栏笆,注意循環(huán)的跳出條件 再看看
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode insertIntoBST(TreeNode root, int val) {
if(root == null) return new TreeNode(val);
TreeNode ans = root;
while(root != null){
if(root.left == null && root.val > val){
root.left = new TreeNode(val);
break;
} else if(root.right == null && root.val < val){
root.right = new TreeNode(val);
break;
}
if(root.val < val){
root = root.right;
} else if (root.val > val){
root = root.left;
}
}
return ans;
}
}
中序遍歷二叉樹,數(shù)組單調(diào)遞增
long long a = long_MIN 要比int的最小值更小
雙指針優(yōu)化 要注意判斷pre != null
450. 刪除二叉搜索樹中的節(jié)點(diǎn)
題目鏈接:450. 刪除二叉搜索樹中的節(jié)點(diǎn)
- 有受害者節(jié)點(diǎn)的情況其實(shí)就是將root.left騰出來(lái)為null. 然后return root.right.
else {
TreeNode curr = root.right;
while(curr.left!=null){
curr = curr.left;
}
curr.left = root.left;
return root.right;
}