本文主要是介绍力扣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);}
}
这篇关于力扣labuladong——一刷day69的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!