1

JZ-062-二叉查找树的第 K 个结点

 2 years ago
source link: https://segmentfault.com/a/1190000041415671
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

JZ-062-二叉查找树的第 K 个结点

发布于 2 月 16 日

二叉查找树的第 K 个结点

给定一棵二叉搜索树,请找出其中的第k小的结点。

题目链接: 二叉查找树的第 K 个结点

/**
 * 标题:二叉查找树的第 K 个结点
 * 题目描述
 * 给定一棵二叉搜索树,请找出其中的第k小的结点。
 * 题目链接:
 * https://www.nowcoder.com/practice/ef068f602dde4d28aab2b210e859150a?tpId=13&&tqId=11215&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
 */
public class Jz62 {

    private TreeNode result;
    private int cnt;

    /**
     * 中序遍历
     *
     * @param pRoot
     * @param k
     * @return
     */
    TreeNode kthNode(TreeNode pRoot, int k) {
        inOrder(pRoot, k);
        return result;
    }

    private void inOrder(TreeNode root, int k) {
        if (root == null || cnt >= k) {
            return;
        }
        inOrder(root.left, k);
        cnt++;
        if (cnt == k) {
            result = root;
        }
        inOrder(root.right, k);
    }

    public static void main(String[] args) {

    }
}

【每日寄语】 轻松时记得努力,忙碌时别忘了梦想。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK