题解 | #二叉搜索树的第k个节点#

二叉搜索树的第k个节点

http://www.nowcoder.com/practice/57aa0bab91884a10b5136ca2c087f8ff

import java.util.; import java.util.ArrayList; /

  • public class TreeNode {
  • int val = 0;
  • TreeNode left = null;
  • TreeNode right = null;
  • public TreeNode(int val) {
  • this.val = val;
    
  • }
  • } */

public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param proot TreeNode类 * @param k int整型 * @return int整型 */ public int KthNode (TreeNode proot, int k) { if(proot==null){ return -1; } ArrayList nodelist=getNum(proot); if(nodelist.size()<k||k==0){ return -1; } Collections.sort(nodelist); return Integer.valueOf(nodelist.get(k-1)); } public ArrayList getNum (TreeNode proot ) { ArrayList list=new ArrayList(); if(proot!=null){ list.add(proot.val); }else{ return null; } if(proot.left!=null){ list.addAll(getNum(proot.left)); } if(proot.right!=null){ list.addAll(getNum(proot.right)); } return list; } }

全部评论

相关推荐

1 收藏 评论
分享
牛客网
牛客企业服务