11.Search Range in Binary Search Tree-二叉查找树中搜索区间(中等题)

来源:互联网 发布:淘宝发货地海外 编辑:程序博客网 时间:2024/06/05 16:03

二叉查找树中搜索区间

  1. 题目

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

  2. 样例

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

  3. 题解

二叉查找树的中序遍历,可参考67.Binary Tree Inorder Traversal-二叉树的中序遍历(容易题)和85.Insert Node in a Binary Search Tree-在二叉查找树中插入节点(容易题)

/** * 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.     */    private ArrayList<Integer> list = new ArrayList<>();    public ArrayList<Integer> searchRange(TreeNode root, int k1, int k2) {        if (root == null)        {            return list;        }        searchRange(root.left,k1,k2);        if (root.val >= k1 && root.val <= k2)        {            list.add(root.val);        }        searchRange(root.right,k1,k2);        return list;    }}

Last Update 2016.9.20

0 0
原创粉丝点击