The sword refers to the offer-question 63: the kth node of the binary search tree

Topic description

Given a binary search tree, find the kth largest node in it. For example, in 5 / \ 3 7 /\ /\ 2 4 6 8, the value of the third node in the numerical order of the nodes is 4.

Experimental platform: Niuke.com


Solutions:

write picture description here

java:

/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;
    }
}
*/
public class Solution {
    int k = 0;

    TreeNode KthNode(TreeNode pRoot, int k) {
        if (pRoot == null || k == 0) {
            return null;
        }
        this.k = k;
        return getKthNode(pRoot);
    }

    TreeNode getKthNode(TreeNode pRoot) {
        TreeNode target = null;
        if (pRoot.left != null) {
            target = getKthNode(pRoot.left);
        }
        if (target == null) {
            if (k == 1) {
                target = pRoot;
            } else {
                k--;
            }
        }
        if (target == null && pRoot.right != null) {
            target = getKthNode(pRoot.right);
        }
        return target;
    }
}

python:

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324774411&siteId=291194637