题解 | #二叉搜索树的第k个节点#
二叉搜索树的第k个节点
http://www.nowcoder.com/practice/57aa0bab91884a10b5136ca2c087f8ff
先遍历,之后放入集合,注意遍历二叉树的选型
import java.util.*;
/*
* 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) {
// write code here
if(proot==null) { return -1;}
ArrayList<Integer> list = new ArrayList<Integer>();
ArrayList<Integer> aa = AA(proot, list);
//注意对k条件的判断
// return aa.get(k-1);
return k>0&&k<=list.size()?list.get(k-1):-1;
}
//将节点放入集合中进行排序之后返回,再获取
public static ArrayList<Integer> AA(TreeNode root,ArrayList list) {
if (root != null) {
AA(root.left, list);
list.add(root.val);
// System.out.println(root.val);
AA(root.right, list);
}
Collections.sort(list);
return list;
}
}
idea代码
package com.yzcOfffer.JZ54.ss;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
/**
* @author YZC
* @date 2021/12/5 21:34
*/
class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
public class Solution {
public static void main(String[] args) {
TreeNode node1 = new TreeNode(1);
// TreeNode node2 = new TreeNode(2);
// TreeNode node3 = new TreeNode(3);
// TreeNode node4 = new TreeNode(4);
// TreeNode node5 = new TreeNode(5);
// node1.left = node2;
// node1.right = node3;
// node3.left = node4;
// node3.right = node5;
// KthNode(node1,3);
// List aa = AA(node1, list);
List aa = demo(node1, list);
System.out.println(aa);
}
static List list = new ArrayList<Integer>();
public static List AA(TreeNode root, List list) {
if (root != null) {
AA(root.left, list);
list.add(root.val);
System.out.println(root.val);
AA(root.right, list);
}
Collections.sort(list);
return list;
}
public static List demo(TreeNode root, List list) {
if (root.left != null) {
demo(root.left, list);
}
System.out.println(root.val);
list.add(root.val);
if (root.right!= null) {
demo(root.right, list);
}
return list;
}
public static int KthNode(TreeNode proot, int k) {
if (proot != null) {
KthNode(proot.left, k);
list.add(proot.val);
KthNode(proot.right, k);
}
Collections.sort(list);
System.out.println(list);
return 1;
// if (proot.left != null) {
// KthNode(proot.left, k);
// }
// list.add(proot.val);
// System.out.println(proot.val);
// if (proot.right != null) {
// KthNode(proot.right, k);
// }
// if (proot.left == null&&proot.right == null) {
// Collections.sort(list);
// System.out.println(list);
// }
// return 1;
}
// public static Collection<Integer> group(TreeNode proot){
//
// }
}
