题目:二叉查找树中搜索区间

来源:互联网 发布:细说php下载 编辑:程序博客网 时间:2024/05/22 17:10

给定两个值 k1 和 k2(k1 < k2)和一个二叉查找树的根节点。找到树中所有值在 k1 到 k2 范围内的节点。即打印所有x (k1 <= x <= k2) 其中 x 是二叉查找树的中的节点值。返回所有升序的节点值。

您在真实的面试中是否遇到过这个题?

Yes





样例

如果有 k1 = 10 和 k2 = 22, 你的程序应该返回 [12, 20, 22].
    20
   /  \
  8   22
/ \
4   12

标签 Expand   



相关题目 Expand   

解题思路:
用递归实现,root满足条件时候,将root加入List中,再递归左右子树,若root<K1时,则表示只有在root的右子树才存在满足条件的节点,同理root>k2,只有root的左子树才存在
/*** 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> searchList = new ArrayList<>();    public ArrayList<Integer> searchRange(TreeNode root, int k1, int k2) {        // write your code here         if(null==root) return searchList;         if(root.val>=k1&&root.val<=k2){              searchList.add(root.val);             searchRange(root.left, k1, k2);             searchRange(root.right, k1, k2);         }else if(root.val<k1){             searchRange(root.right, k1, k2);         }else if(root.val>k2){             searchRange(root.left, k1, k2);         }         Collections.sort(searchList);         return searchList;    }}

0 0
原创粉丝点击