zoukankan      html  css  js  c++  java
  • [LeetCode]404. 左叶子之和(递归)、938. 二叉搜索树的范围和(递归)(BST)

    题目 404. 左叶子之和

    如题

    题解

    • 类似树的遍历的递归
    • 注意一定要是叶子结点

    代码

    class Solution {
        public int sumOfLeftLeaves(TreeNode root) {
            if(root == null){return 0;}
    
            int sum = sumOfLeftLeaves(root.left)+sumOfLeftLeaves(root.right);
            if(root.left!=null&&root.left.left==null&&root.left.right==null){
                    sum+=root.left.val;
            }
    
            return sum;
        }
    }
    

    题目 938. 二叉搜索树的范围和

    题解

    • 递归

    代码

    class Solution {
        public int rangeSumBST(TreeNode root, int L, int R) {
            if(root == null){return 0;}
    
            if(root.val>=L&&root.val<=R){
                return root.val+rangeSumBST(root.left,L,R)+rangeSumBST(root.right,L,R);
            }else if(root.val<=L){
                return rangeSumBST(root.right,L,R);
            }else{
                return rangeSumBST(root.left,L,R);
            }
        }
    }
    
  • 相关阅读:
    在普通类中调用service
    layui util 工具时间戳转换
    最大值
    药房管理
    线段树2
    线段树1
    Dijkstra
    最大值最小化
    图的M 着色问题
    取余运算
  • 原文地址:https://www.cnblogs.com/coding-gaga/p/13061775.html
Copyright © 2011-2022 走看看