classTreeNode{ int val; TreeNode left; TreeNode right;
TreeNode(int x) { val = x; } }
//递归实现深度优先搜索 publicclass 二叉搜索树的范围和 { staticint result; staticint ans; publicstaticvoidmain(String[] args){ result = 0; //第一层 TreeNode node = new TreeNode(10); //第二层 node.left = new TreeNode(5); node.right = new TreeNode(15); //第三层 node.left.left = new TreeNode(3); node.left.right = new TreeNode(7); node.right.right = new TreeNode(18); //法一,递归但是方法作用与法二不同,递归实现深度优先遍历: // dfs(node,7, 15); // System.out.println(result); //法二: // System.out.println(dfs2(node,7,15)); //法三,迭代实现深度优先遍历: f3(node,7,15); System.out.println(ans);
}
法一:
1 2 3 4 5 6 7 8 9 10 11
//当前节点是否能进入result的和,遍历了所有节点 publicstaticvoiddfs(TreeNode node, int l, int r){ if (node != null){ if (l <= node.val && node.val <= r) { result += node.val; } //这里必须要遍历每个节点,所以需要node.val > l ,dfs(node.left,l,r) if (node.val > l) dfs(node.left,l,r); if (node.val < r) dfs(node.right,l,r); } }
法二:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
//该树的满足范围的和,,没有遍历所有节点 //如果当前节点的值小于left,和等于右子数之和 //如果当前节点的值大于right,和等于左子数之和 //如果当前节点的值在范围里,和等于右子数+左子树之和+当前节点的值 privatestaticintdfs2(TreeNode node, int l, int r){ if (node == null) { return0; } if (node.val < l){ return dfs2(node.right,l,r); } if (node.val > r){ return dfs2(node.left,l,r); } return dfs2(node.left,l,r)+dfs2(node.right,l,r)+node.val; }
法三:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
//迭代实现深度优先遍历,遍历了所有节点 publicstaticintf3(TreeNode root,int L, int R){ 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; }