Kth Smallest Element in a BST

题目链接

思想:左序搜索,在遍历的时候,用一个记录变量记录已经确定的点,因为小的点总是先访问到,每确定一个节点减去1。知道为零时候则是最k小的

class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode(int x) { val = x; }
  }

public class Solution {
    public int kthSmallest(TreeNode root, int k) {
        int record[]=new int[1];
        record[0]=k;
        return DFS(root, record).val;
    }

    public TreeNode DFS(TreeNode root,int record[])
    {
        if(record[0]==0)
        {
            return root;
        }

        TreeNode temp=null;
        if(root.left!=null)
        {
            temp=DFS(root.left, record);
            if(temp!=null)
            {
                return temp;
            }
        }
        record[0]--;
        if(record[0]==0)
        {
            return root;
        }

        if(root.right!=null)
        {
            temp=DFS(root.right, record);
            if(temp!=null)
            {
                return temp;
            }
        }
        if(record[0]==0)
        {
            return root;
        }

        return null;
    }
}

你可能感兴趣的:(Kth Smallest Element in a BST)