classSolution{publicintkthSmallest(TreeNode root,int k){inorder(root);if(root==null){return-1;}return res.get(k-1);}List<Integer> res =newArrayList<>();publicList<Integer>inorder(TreeNode root){// 中序if(root==null){return res;}// 栈和指针TreeNode cur = root;Stack<TreeNode> st =newStack<>();while(cur!=null||!st.isEmpty()){if(cur!=null){
st.add(cur);
cur = cur.left;}else{
cur = st.pop();
res.add(cur.val);
cur = cur.right;}}return res;}}
3- ACM 实现
publicclass kthSmallest {publicstaticclassTreeNode{int val;TreeNode left;TreeNode right;TreeNode(){}TreeNode(int val){this.val = val;}TreeNode(int val,TreeNode left,TreeNode right){this.val = val;this.left = left;this.right = right;}}publicstaticTreeNodebuild(String str){if(str ==null|| str.length()==0){returnnull;}String input = str.replace("[","");
input = input.replace("]","");String[] parts = input.split(",");Integer[] nums =newInteger[parts.length];for(int i =0; i < parts.length;i++){if(!parts[i].equals("null")){
nums[i]=Integer.parseInt(parts[i]);}else{
nums[i]=null;}}Queue<TreeNode> queue =newLinkedList<>();TreeNode root =newTreeNode(nums[0]);
queue.offer(root);int index =1;while(!queue.isEmpty()&& index<parts.length){TreeNode node = queue.poll();if(index<nums.length && nums[index]!=null){
node.left =newTreeNode(nums[index]);
queue.offer(node.left);}
index++;if(index<nums.length && nums[index]!=null){
node.right =newTreeNode(nums[index]);
queue.offer(node.right);}
index++;}return root;}publicstaticintkthSmallest(TreeNode root,int k){inorder(root);if(root==null){return-1;}return res.get(k-1);}staticList<Integer> res =newArrayList<>();publicstaticList<Integer>inorder(TreeNode root){// 中序if(root==null){return res;}// 栈和指针TreeNode cur = root;Stack<TreeNode> st =newStack<>();while(cur!=null||!st.isEmpty()){if(cur!=null){
st.add(cur);
cur = cur.left;}else{
cur = st.pop();
res.add(cur.val);
cur = cur.right;}}return res;}publicstaticvoidmain(String[] args){Scanner sc =newScanner(System.in);String input = sc.nextLine();TreeNode root =build(input);System.out.println("输入k");int k = sc.nextInt();System.out.println("结果是"+kthSmallest(root,k));}}