当前位置:网站首页>Jz-062- the k-th node of binary search tree

Jz-062- the k-th node of binary search tree

2022-06-26 20:07:00 Lion, tiger and leopard

The second of the binary search tree K Nodes

Title Description

Given a binary search tree , Please find out the No k Small node .

Topic link : The second of the binary search tree K Nodes

Code

/**
 *  title : The second of the binary search tree  K  Nodes 
 *  Title Description 
 *  Given a binary search tree , Please find out the No k Small node .
 *  Topic link :
 * 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;

    /**
     *  In the sequence traversal 
     *
     * @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) {

    }
}
【 Daily message 】 Remember to work hard when you're relaxed , Don't forget your dreams when you are busy .
原网站

版权声明
本文为[Lion, tiger and leopard]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202161727564581.html