Kth Smallest Element in a BST

来源:互联网 发布:java 中英文字符长度 编辑:程序博客网 时间:2024/04/24 16:34

题目链接

思想:左序搜索,在遍历的时候,用一个记录变量记录已经确定的点,因为小的点总是先访问到,每确定一个节点减去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;    }}
0 0