中序遍歷 爲 “左、根、右” 順序,遞歸代碼:
// 打印中序遍歷
void dfs(TreeNode root) {
if(root == null) return;
dfs(root.left); // 左
System.out.println(root.val); // 根
dfs(root.right); // 右
}
中序遍歷的倒序 爲 “右、根、左” 順序,遞歸法代碼如下:
// 打印中序遍歷倒序
void dfs(TreeNode root) {
if(root == null) return;
dfs(root.right); // 右
System.out.println(root.val); // 根
dfs(root.left); // 左
}
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private int res=0,cnt=0;
public int kthLargest(TreeNode root, int k) {
dfs(root,k);
return res;
}
private void dfs(TreeNode root,int k){
if(root==null) return;
dfs(root.right,k);
if(++cnt==k)
res=root.val;
dfs(root.left,k);
}
}