劍指offer-題63:二叉搜尋樹的第k個結點
阿新 • • 發佈:2019-02-13
題目描述
給定一顆二叉搜尋樹,請找出其中的第k大的結點。例如, 5 / \ 3 7 /\ /\ 2 4 6 8 中,按結點數值大小順序第三個結點的值為4。
實驗平臺:牛客網
解決思路:
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:
略