問題:
給一個二元搜尋樹,還有兩個值,將二元搜尋樹內介於這兩個值的元素相加.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
class Solution { public int rangeSumBST(TreeNode root, int L, int R) { if(root!=null){ if(root.val<L){ return rangeSumBST(root.right,L,R); }else if(root.val>R){ return rangeSumBST(root.left,L,R); }else{ return rangeSumBST(root.left,L,R)+root.val+rangeSumBST(root.right,L,R); } } return 0; } }
|
心得:
這題很簡單,只要了解它定義的二元搜尋樹,就可以使用遞迴解決.