本文主要是介绍LeetCode第938题 - 二叉搜索树的范围和,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目
解答
方案一:递归
class Solution {private int sum = 0;public void inorder(TreeNode node, int low, int high) {if (node == null) {return;}inorder(node.left, low, high);if (node.val >= low && node.val <= high) {sum += node.val;}inorder(node.right, low, high);}public int rangeSumBST(TreeNode root, int low, int high) {inorder(root, low, high);return sum;}
}
方案二:广度优先
class Solution {public int rangeSumBST(TreeNode root, int low, int high) {if (root == null) {return 0;}int sum = 0;LinkedList<TreeNode> nodes = new LinkedList<>();nodes.add(root);while (!nodes.isEmpty()) {TreeNode node = nodes.pop();if (node.val >= low && node.val <= high) {sum += node.val;}if (node.left != null) {nodes.add(node.left);}if (node.right != null) {nodes.add(node.right);}}return sum;}
}
方案三:深度优先
class Solution {public int rangeSumBST(TreeNode root, int low, int high) {if (root == null) {return 0;}int sum = 0;LinkedList<TreeNode> nodes = new LinkedList<>();nodes.add(root);while (!nodes.isEmpty()) {TreeNode node = nodes.pop();if (node.val >= low && node.val <= high) {sum += node.val;}if (node.left != null) {nodes.addFirst(node.left);}if (node.right != null) {nodes.addFirst(node.right);}}return sum;}
}
要点
在遍历的过程中,顺便完成求解。
这篇关于LeetCode第938题 - 二叉搜索树的范围和的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!