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

654. 最大二叉树

public TreeNode ConstructMaximumBinaryTree(int[] nums) {
        if (nums.Length == 1) return new TreeNode(nums[0]);
            int maxValue = Int32.MinValue;
            int index = 0;
            for (int i = 0; i < nums.Length; i++)
            {
                if (nums[i] > maxValue)
                {
                    maxValue = nums[i];
                    index = i;
                }
            }
            TreeNode node = new TreeNode(maxValue);
            if (index > 0)
            {
                int[] left = new int[index];
                for (int i = 0; i < index; i++)
                {
                    left[i] = nums[i];
                }
                node.left = ConstructMaximumBinaryTree(left);
            }
            if (index < nums.Length - 1)
            {
                int[] right = new int[nums.Length - index-1];
                for (int i = 0; i < nums.Length - index - 1; i++)
                {
                    right[i] = nums[index+i+1];
                }
                node.right = ConstructMaximumBinaryTree(right);
            }
            return node;
    }

617. 合并二叉树

public TreeNode MergeTrees(TreeNode root1, TreeNode root2) {
        if(root1 == null && root2 == null) return null;
        if(root1 == null && root2 != null) return root2;//只要有一方为null,就返回另一方
        if(root1 != null && root2 == null) return root1;//只要有一方为null,就返回另一方
        TreeNode node = new TreeNode(0);
        node.val = root1.val + root2.val;
        if(root1.left != null || root2.left != null)
        {
            node.left = MergeTrees(root1.left, root2.left);
        }
        if(root1.right != null || root2.right != null)
        {
            node.right = MergeTrees(root1.right, root2.right);
        }
        return node;
    }

700. 二叉搜索树中的搜索

public TreeNode SearchBST(TreeNode root, int val) {
        if(root == null) return null;
        if(root.val == val) return root;
        else if(root.val > val) return SearchBST(root.left, val);
        else return SearchBST(root.right, val);
    }

98. 验证二叉搜索树

误区:
误区

思路:需要一个全局的变量记作maxValue,使得中序遍历的过程中,不断更新最大值。

public class Solution {
    private long maxVal = Int64.MinValue;//因为节点值最小为Int32.MinValue
    public bool IsValidBST(TreeNode root) {
        if(root == null) return true;
        bool left = IsValidBST(root.left);
        if(maxVal < root.val) maxVal = root.val;
        else return false;
        bool right = IsValidBST(root.right);
        return left && right;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值