leetcode--Kth Smallest Element in a BST

来源:互联网 发布:js 特殊字符校验 编辑:程序博客网 时间:2024/06/11 03:06

Given a binary search tree, write a function kthSmallest to find thekth smallest element in it.

Note:
You may assume k is always valid, 1 ≤ k ≤ BST's total elements.

Follow up:
What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine?

Hint:

  1. Try to utilize the property of a BST.
  2. What if you could modify the BST node's structure?
  3. The optimal runtime complexity is O(height of BST).


题意:在BST树中,查找第k小的节点值

分类:二叉树


解法1:BST树很多问题我们都可以使用中序遍历来解决,这个也不例外

我们设置一个当前访问的元素个数cur,在中序遍历过程中,每要访问一个节点,cur加1

当cur和k相等时,这就是我们要找的节点,返回即可


利用递归来进行中序遍历,如果左子树找不到,则判断是不是当前节点,不是,则在右子树接着找

如果左子树找到了,直接返回

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public int cur = 0;    public int kthSmallest(TreeNode root, int k) {        TreeNode res = inorder(root,k);        if(res!=null) return res.val;        return -1;    }        public TreeNode inorder(TreeNode root,int k){        if(root==null) return null;        if(root.left!=null){            TreeNode left = inorder(root.left,k);//先在左子树找            if(left!=null) return left;//如果找到了,返回        }        cur++;//每次访问节点,都加1        if(cur==k) return root;//判断是不是当前节点        if(root.right!=null){//最后在右子树找            TreeNode right = inorder(root.right,k);            if(right!=null) return right;        }        return null;    }}


0 0
原创粉丝点击