617.合并二叉树
好久没有遇到过这么友好的二叉树题目了呜呜呜,关键点在于考虑好终止条件:当root1或root2为空时,返回另一个root。
/**
* 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 mergeTrees(TreeNode root1, TreeNode root2) {
if (root1 == null) return root2;
if (root2 == null) return root1;
root1.val = root1.val + root2.val;
root1.left = mergeTrees(root1.left, root2.left);
root1.right = mergeTrees(root1.right, root2.right);
return root1;
}
}
230.二叉搜索树中第k小的元素
二叉搜索树(Binary Search Tree,BST),是红黑树、B+树等等的基础,左子树比根节点小,右子树比根节点大,如果使用中序遍历BST树,可以得到升序数组。
这道题先通过中序遍历得到升序列表,然后返回第k - 1个值
class Solution {
List<Integer> list = new ArrayList<>();
public int kthSmallest(TreeNode root, int k) {
inorder(root);
return list.get(k - 1);
}
public void inorder(TreeNode root) {
if (root == null) return ;
inorder(root.left);
list.add(root.val);
inorder(root.right);
}
}
算法复杂度太高,如果要求提高肯定ac不了。
98. 验证二叉搜索树
不能单纯只考虑当前结点的左右子树是否满足要求,要考虑整棵二叉树的合法性,因此给每一个结点一个限定范围,max和min。
class Solution {
public boolean isValidBST(TreeNode root) {
return valid(root, null, null);
}
public boolean valid(TreeNode root, TreeNode max, TreeNode min) {
if (root == null) return true;
if (max != null && max.val <= root.val) return false;
if (min != null && min.val >= root.val) return false;
return valid(root.left, root, min) && valid(root.right, max, root);
}
}
700. 二叉搜索树中的搜索
直接写代码,用root的值进行二分查找即可。
class Solution {
public TreeNode searchBST(TreeNode root, int val) {
if (root == null) return null;
if (root.val == val) return root;
if (root.val > val) return searchBST(root.left, val);
if (root.val < val) return searchBST(root.right, val);
return null;
}
}
day17完结撒花~,第一题day16中做过啦!明天是实习最后一天,要回去秋招,黑暗的日子要来了。