题目
二叉查找树中搜索区间
给定两个值 k1 和 k2(k1 < k2)和一个二叉查找树的根节点。找到树中所有值在 k1 到 k2 范围内的节点。即打印所有x (k1 <= x <= k2) 其中 x 是二叉查找树的中的节点值。返回所有升序的节点值。
样例
如果有 k1 = 10
和 k2 = 22
, 你的程序应该返回 [12, 20, 22]
.
20
/ \
8 22
/ \
4 12
解题
已经是二叉排序树了,中序遍历的结果就是升序的,然后在升序的序列中找到符合条件的部分节点就好了
/** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } */ public class Solution { /** * @param root: The root of the binary search tree. * @param k1 and k2: range k1 to k2. * @return: Return all keys that k1<=key<=k2 in ascending order. */ public ArrayList<Integer> searchRange(TreeNode root, int k1, int k2) { // write your code here ArrayList<Integer> inorder = inorderTraveral(root); ArrayList<Integer> result = new ArrayList<Integer>(); for(int i=0;i< inorder.size();i++){ int tmp = inorder.get(i); if(k1<= tmp && tmp <= k2){ result.add(tmp); } } return result; } public ArrayList<Integer> inorderTraveral(TreeNode root){ ArrayList<Integer> inorder = new ArrayList<Integer>(); if(root == null){ return inorder; } inorder.addAll(inorderTraveral(root.left)); inorder.add(root.val); inorder.addAll(inorderTraveral(root.right)); return inorder; } }
Java Code
也可以直接中序遍历过程中,符合条件的节点值加入到ArrayList中去
/** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } */ public class Solution { /** * @param root: The root of the binary search tree. * @param k1 and k2: range k1 to k2. * @return: Return all keys that k1<=key<=k2 in ascending order. */ public ArrayList<Integer> searchRange(TreeNode root, int k1, int k2) { // write your code here ArrayList<Integer> inorder = inorderTraveral(root,k1,k2); return inorder; } public ArrayList<Integer> inorderTraveral(TreeNode root,int k1,int k2){ ArrayList<Integer> inorder = new ArrayList<Integer>(); if(root == null){ return inorder; } inorder.addAll(inorderTraveral(root.left,k1,k2)); if( root.val >= k1 && root.val <= k2) inorder.add(root.val); inorder.addAll(inorderTraveral(root.right,k1,k2)); return inorder; } }
Java Code
Python 实现
Python 中 append 是在list 后面添加元素
+= 是连接两个list
""" Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ class Solution: """ @param root: The root of the binary search tree. @param k1 and k2: range k1 to k2. @return: Return all keys that k1<=key<=k2 in ascending order. """ def searchRange(self, root, k1, k2): # write your code here return self.inorderTraveral(root,k1,k2) def inorderTraveral(self,root,k1,k2): inorder = list() if root == None: return inorder left = self.inorderTraveral(root.left,k1,k2) if len(left)!=0: inorder += left if root.val>= k1 and root.val <= k2: inorder.append(root.val) right = self.inorderTraveral(root.right,k1,k2) if len(right)!=0: inorder += right return inorder