LeetCode 230:Kth Smallest Element in a BST

题意描述

给定一个二叉搜索树,编写一个函数kthSmallest在其中找到第k个最小的元素。

测试用例

Example 1:

Input: root = [3,1,4,null,2], k = 1
   3
  / \
 1   4
  \
   2
Output: 1

Example 2:

Input: root = [5,3,6,2,4,null,null,1], k = 3
       5
      / \
     3   6
    / \
   2   4
  /
 1
Output: 3

解题思路

使用中序遍历二叉树,因为是二叉搜索树,所以第k个节点就是结果

一、非递归

    private static int count = 0;
        public int kthSmallest(TreeNode root, int k) {
            count = k;
            if(root == null) return -1;
            Stack<TreeNode> stack = new Stack<>();
            stack.push(root);
            TreeNode p = root;
            while(p != null || !stack.isEmpty()){
                while(p != null){
                    stack.push(p);
                    p = p.left;
                }
                if(!stack.isEmpty()){
                    TreeNode node = stack.pop();
                    count --;
                    if(count == 0) return node.val;
                    if(node.right != null)  p = node.right;
                }
            }
            return -1;
        }

二、递归

    private static int count = 0;
        private static int val = -1;
        public int kthSmallest(TreeNode root, int k) {
            if(root == null) return -1;
            count = k;
            node(root);
            return val;
        }
        private void node(TreeNode root){
            if(root.left != null) node(root.left);
            count --;
            if(count == 0){
                val = root.val;
                return;
            }
            if(root.right != null) node(root.right);
        }
posted @ 2020-06-01 23:30  灵图  阅读(80)  评论(0编辑  收藏  举报