力扣labuladong——一刷day69

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

文章目录

  • 前言
  • 一、力扣669. 修剪二叉搜索树
  • 二、力扣671. 二叉树中第二小的节点


前言


二叉树的递归分为「遍历」和「分解问题」两种思维模式,这道题需要用到「遍历」的思维模式。

一、力扣669. 修剪二叉搜索树

/**
 * 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 trimBST(TreeNode root, int low, int high) {
        if(root == null){
            return null;
        }
        if(root.val < low){
            return trimBST(root.right,low,high);
        }
        if(root.val > high){
            return trimBST(root.left, low, high);
        }
        root.left = trimBST(root.left, low, high);
        root.right = trimBST(root.right, low, high);
        return root;
    }
}

二、力扣671. 二叉树中第二小的节点

/**
 * 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 int findSecondMinimumValue(TreeNode root) {
        if(root.left == null && root.right == null){
            return -1;
        }
        int left = root.left.val, right = root.right.val;
        if(root.val == root.left.val){
            left = findSecondMinimumValue(root.left);
        }
        if(root.val == root.right.val){
            right = findSecondMinimumValue(root.right);
        }
        if(left == -1){
            return right;
        }
        if(right == -1){
            return left;
        }
        return Math.min(left,right);
    }
}

你可能感兴趣的:(力扣题解,leetcode,算法,职场和发展,java,数据结构)