【LeetCode】938. 二叉搜索樹的範圍和

題目描述

給定二叉搜索樹的根結點 root,返回 LR(含)之間的所有結點的值的和。

二叉搜索樹保證具有唯一的值。

示例

  • 示例1

輸入:root = [10,5,15,3,7,null,18], L = 7, R = 15
輸出:32

  • 示例2

輸入:root = [10,5,15,3,7,13,18,1,null,6], L = 6, R = 10
輸出:23

提示

  1. 樹中的結點數量最多爲 10000 個。
  2. 最終的答案保證小於 2^31

解答

  • 自己答案
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int rangeSumBST(TreeNode root, int L, int R) {
        if(root.left==null&&root.right==null){
            if(root.val>=L&&root.val<=R){
                return root.val;
            }else{
                return 0;
            }
        }else if(root.left!=null&&root.right==null){
            if(root.val>=L&&root.val<=R){
                return rangeSumBST(root.left,L,R)+root.val;
            }else{
                return rangeSumBST(root.left,L,R);
            }
            
        }else if(root.left==null&&root.right!=null){
            if(root.val>=L&&root.val<=R){
                return rangeSumBST(root.right,L,R)+root.val;
            }else{
                return rangeSumBST(root.right,L,R);
            }
            
        }else{
            if(root.val>=L&&root.val<=R){
                return rangeSumBST(root.left,L,R)+rangeSumBST(root.right,L,R)+root.val;
            }else{
                return rangeSumBST(root.left,L,R)+rangeSumBST(root.right,L,R);
            }
            
        }
        
        
    }
}
  • 其它答案一
public int rangeSumBST(TreeNode root, int L, int R) {
        if (root == null) {
            return 0;
        }
        if (root.val < L) {
            return rangeSumBST(root.right, L, R);
        }
        if (root.val > R) {
            return rangeSumBST(root.left, L, R);
        }
        return root.val + rangeSumBST(root.left, L, R) + rangeSumBST(root.right, L, R);
    }

  • 其它答案二
class Solution {
    public int rangeSumBST(TreeNode root, int L, int R) {
        int ans = 0;
        Stack<TreeNode> stack = new Stack();
        stack.push(root);
        while (!stack.isEmpty()) {
            TreeNode node = stack.pop();
            if (node != null) {
                if (L <= node.val && node.val <= R)
                    ans += node.val;
                if (L < node.val)
                    stack.push(node.left);
                if (node.val < R)
                    stack.push(node.right);
            }
        }
        return ans;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章