LeetCode From Easy To Hard No4[Easy]: Range Sum of BST 求二叉树某个区间内的数的和

给定一个二叉搜索树的节点,求解该树中值在指定范围内的所有节点之和。本文介绍如何通过递归方法解决此问题,并探讨二叉树的不同遍历方式。
摘要由CSDN通过智能技术生成

Given the root node of a binary search tree, return the sum of values of all nodes with value between L and R(inclusive).

The binary search tree is guaranteed to have unique values.

 

Example 1:

Input: root = [10,5,15,3,7,null,18], L = 7, R = 15
Output: 32

Example 2:

Input: root = [10,5,15,3,7,13,18,1,null,6], L = 6, R = 10
Output: 23

 

Note:

  1. The number of nodes in the tree is at most 10000.
  2. The final answer is guaranteed to be less than 2^31.

方法顺序:

1.定义二叉树结构。

2.通过数组创建二叉树以便测试。

3.编写区间求和方法(两种情况,

①如根节点值在区间内,则加上根节点值,左右节点继续判断是否在区间内然后递归求和;

②如根节点不在区间内,则直接左右节点继续判断是否在区间内然后递归求和

)。

package test;

class Solution {
    /**
     * 1. 定义二叉树结构
     */
    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }

    /**
     * 2. 数组转化为完全二叉树结构
     *
     * @param array 数组
     * @param index 下标
     * @return
     */
     TreeNode createBinaryTreeByArray(Integer[] array, int index) {
        TreeNode tree = null;
        if (index < array.length) {
            Integer value = array[index];
            if (value == null) return null;
            tree = new TreeNode(value);
            tree.left = createBinaryTreeByArray(array, 2 * index + 1);
            tree.right = createBinaryTreeByArray(array, 2 * index + 2);
        }
        return tree;
    }

    /**
     * 3. 二叉树区间求和
     * @param root 二叉树根节点
     * @param L 左区间 (包含)
     * @param R 右区间 (包含)
     * @return 区间和
     */
    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);
        }
        // 如根节点不在区间内,则直接左右节点继续判断是否在区间内然后递归求和
        return rangeSumBST(root.left, L, R) + rangeSumBST(root.right, L, R);
    }


    public static void main(String[] args){
        Integer[] datas = new Integer[]{10,5,15,3,7,13,18,1,null,6};
        Solution solution = new Solution();
        TreeNode root = solution.createBinaryTreeByArray(datas, 0);
        System.out.println(solution.rangeSumBST(root, 7, 15));
    }

}

参考一下一些大牛在discuss中的解法,可以 reduce the nodes we need to travel~

public int rangeSumBST(TreeNode root, int L, int R) {
        if (root == null)
            return 0;
        int sum = 0;
        if (root.val < L)
            sum += rangeSumBST(root.right, L, R);
        if (root.val > R)
            sum += rangeSumBST(root.left, L, R);
        if (root.val >= L && root.val <= R) {
            sum += root.val;
            if (root.val == L)
                sum += rangeSumBST(root.right, L, R);
            else if (root.val == R)
                sum += rangeSumBST(root.left, L, R);
            else {
                sum += rangeSumBST(root.right, L, R);
                sum += rangeSumBST(root.left, L, R);
            }
        }
        return sum;
    }

顺便温习了一下二叉树的四种遍历方法

①前序遍历(先根节点再左最后右)

②中序遍历(先左节点再根最后右)

③后序遍历(先左节点再右最后根)

④层次遍历 (一层一层节点遍历)

 

package test;

import java.util.LinkedList;

class Solution {
    /**
     * 1. 定义二叉树结构
     */
    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }

    /**
     * 2. 数组转化为完全二叉树结构
     *
     * @param array 数组
     * @param index 下标
     * @return
     */
     TreeNode createBinaryTreeByArray(int index, Integer... array) {
        TreeNode tree = null;
        if (index < array.length) {
            Integer value = array[index];
            if (value == null) return null;
            tree = new TreeNode(value);
            tree.left = createBinaryTreeByArray(2 * index + 1, array);
            tree.right = createBinaryTreeByArray(2 * index + 2, array);
        }
        return tree;
    }

    /**
     * 3. 二叉树区间求和
     * @param root 二叉树根节点
     * @param L 左区间 (包含)
     * @param R 右区间 (包含)
     * @return 区间和
     */
    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);
        }
        // 如根节点不在区间内,则直接左右节点继续判断是否在区间内然后递归求和
        return rangeSumBST(root.left, L, R) + rangeSumBST(root.right, L, R);
    }

    //前序遍历
    public void preorder(TreeNode root) {
        if (root == null) return;
        System.out.println(root.val);
        preorder(root.left);
        preorder(root.right);
    }
    //中序遍历
    public void inorder(TreeNode root){
        if (root == null) return;
        inorder(root.left);
        System.out.println(root.val);
        inorder(root.right);

    }
    //    后序遍历
    public void postorder(TreeNode root){
        if (root == null) return;
        postorder(root.left);
        postorder(root.right);
        System.out.println(root.val);

    }

    /**
     * 层次遍历和其他三种遍历不一样,需要借助队列来实现
     * @param root
     */
    public void storeyTraversal(TreeNode root){
        if (root == null) {
            return;
        }
        LinkedList<TreeNode> list = new LinkedList<TreeNode>();
        list.add(root); // 先将根节点放进list
        while (!list.isEmpty()) {

            TreeNode currentNode = list.poll(); // 每次取出并移除list首元素
            if (currentNode != null) {
                System.out.println(currentNode.val);
                if (currentNode.left != null) {
                    list.add(currentNode.left);
                }
                if (currentNode.right != null) {
                    list.add(currentNode.right);
                }
            }
        }

    }

    public static void main(String[] args){
        Integer[] datas = new Integer[]{10,5,15,3,7,13,18,1,null,6};
        Solution solution = new Solution();
        TreeNode root = solution.createBinaryTreeByArray(0, datas);
//        System.out.println(solution.rangeSumBST(root, 6, 10));
//        solution.preorder(root);
//        solution.inorder(root);
//        solution.postorder(root);
        solution.storeyTraversal(root);
    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值