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

二叉搜索树的第k个结点

http://www.nowcoder.com/practice/ef068f602dde4d28aab2b210e859150a

二叉搜索树特性:
左孩子 < 根节点 < 右孩子
可以利用二叉树的中序遍历得到答案

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 {
    TreeNode KthNode(TreeNode pRoot, int k) {

        if (pRoot == null || k < 1) {
            return null;
        }

        List<TreeNode> list = new ArrayList<>();

        treeDeep (pRoot, list);

        if (list.size() < k) {
            return null;
        }

        return list.get(k-1);
    }

    public void treeDeep (TreeNode pRoot, List<TreeNode> list) {

        if (pRoot == null) {
            return;
        }

        treeDeep(pRoot.left, list);
        list.add(pRoot);
        treeDeep(pRoot.right, list);
    }
}
刷刷题 文章被收录于专栏

刷刷题 活跃活跃脑细胞

全部评论

相关推荐

09-19 12:15
门头沟学院 Java
迷茫的大四🐶:这下是真的打牌了,我可以用感谢信和佬一起打牌吗
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务