思路
反着的中序遍历,并计数
代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
//遍历次数
int c=0;
//要找的数字
int cnt;
int result;
boolean enough=false;
//寻找第cnt大的数
public int findTargetNode(TreeNode root, int cnt) {
this.cnt=cnt;
fMidOrder(root);
return result;
}
/**
* 反中序遍历,右中左,遍历一次累计一次,当次数等于cnt,result就是这个数,
* @param root
* @return
*/
public void fMidOrder(TreeNode root) {
//判断是否足够
if (enough||root==null) {
return;
}
//遍历右边
if (root.right!= null) {
fMidOrder(root.right);
}
//遍历自己
c++;
if (c==cnt ) {
result=root.val;
enough=true;
return;
}
//遍历左边
if (root.left!= null) {
fMidOrder(root.left);
}
}
}