forked from CaiFengGH/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
46 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
>题目描述 | ||
返回二叉搜索树中第K大的树节点; | ||
|
||
- 实现方法 | ||
|
||
二叉搜索树的中序遍历的第k个值就是第k大的树节点; | ||
|
||
``` | ||
package DayCode; | ||
/** | ||
* @author Ethan | ||
* @desc 返回二叉搜索树上第K大的树节点 | ||
*/ | ||
public class C63KthNode { | ||
public int count = 0; | ||
/** | ||
* @author Ethan | ||
* @desc 中序遍历时,第k个值就是第K大的值 | ||
*/ | ||
public TreeNode kthNode(TreeNode root,int k){ | ||
//1-递归结束条件 | ||
if(root == null){ | ||
return null; | ||
} | ||
//2-左子树 | ||
TreeNode node = kthNode(root.left,k); | ||
if(node != null){ | ||
return node; | ||
} | ||
//3-自加 | ||
if(++count == k ){ | ||
return root; | ||
} | ||
//4-右子树 | ||
node = kthNode(root.right, k); | ||
if(node != null){ | ||
return node; | ||
} | ||
return null; | ||
} | ||
} | ||
``` |