代码随想录算法训练营第二十天 |654. 最大二叉树、617. 合并二叉树、700. 二叉搜索树中的搜索、98. 验证二叉搜索树

83 阅读1分钟

代码随想录算法训练营第二十天 |654. 最大二叉树、617. 合并二叉树、700. 二叉搜索树中的搜索、98. 验证二叉搜索树

654. 最大二叉树

题目链接:654. 最大二叉树

  • 分解定义:在当前范围的节点中,挑选一个最大值,返回以该最大值为根节点的树。
  • 逻辑正确了但是findMaxIndex那里要注意遍历的数组的范围

617. 合并二叉树

题目链接:617. 合并二叉树

  • 简单题不简单
  • 不需要创建新的节点
  •  class Solution {
         public TreeNode merge(TreeNode root1, TreeNode root2, TreeNode root3){
             //mid
             if(root1 == null && root2 == null) return null;
             if(root1 != null && root2 != null){
                 root3.val = root1.val + root2.val;
             } else if (root1 == null && root2 != null){
                 root3.val = root2.val;
             } else if (root1 != null && root2 == null){
                 root3.val = root1.val;
             }
     ​
             //left
             root3.left = merge(root1 != null? root1.left : null, root2 != null ? root2.left : null, new TreeNode());
             root3.right = merge(root1 != null? root1.right : null, root2 != null ? root2.right : null, new TreeNode());
     ​
             return root3;
         }
         public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
             return merge(root1, root2, new TreeNode(0, null, null));
         }
     }
    

700. 二叉搜索树中的搜索

题目链接:700. 二叉搜索树中的搜索

  • easy
  • 但是注意迭代法

98. 验证二叉搜索树

题目链接:98. 验证二叉搜索树

  • 没那么简单
  •  // 错误代码 要考虑左子树中的数都小于根节点
     class Solution {
         public boolean isValidBST(TreeNode root) {
             boolean flag1 = true;
             boolean flag2 = true;
             if(root.left != null) {
                 if(root.left.val >= root.val) return false;
                 else {
                     flag1 = isValidBST(root.left);
                 }
             }
             if(root.right != null){
                 if(root.right.val <= root.val) return false;
                 else {
                     flag2 = isValidBST(root.right);
                 }
             }
             return flag1 && flag2;
         }
     }
     ​
     //正确
     class Solution {
         long maxValue = Long.MIN_VALUE;
         public boolean isValidBST(TreeNode root) {
             if(root == null) return true;
             boolean flag1 = isValidBST(root.left);
             if(root.val > maxValue) {
                 maxValue = root.val;
             }else return false;
             boolean flag2 = isValidBST(root.right);
     ​
             return flag1 && flag2;
         }
     }
    
  • 中序遍历二叉树,数组单调递增
  • long long a = long_MIN 要比int的最小值更小
  • 双指针优化 要注意判断pre != null