/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */classSolution{privateintk;privateintans;publicintkthLargest(TreeNoderoot,intk){this.k=k;dfs(root);returnans;}privatevoiddfs(TreeNoderoot){if(root==null||k==0){return;}dfs(root.right);if(--k==0){ans=root.val;}dfs(root.left);}}
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */classSolution{public:intkthLargest(TreeNode*root,intk){intans=0;function<void(TreeNode*)>dfs=[&](TreeNode*root){if(!root||!k){return;}dfs(root->right);if(--k==0){ans=root->val;}dfs(root->left);};dfs(root);returnans;}};
1 2 3 4 5 6 7 8 9101112131415161718192021222324
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */funckthLargest(root*TreeNode,kint)(ansint){vardfsfunc(*TreeNode)dfs=func(root*TreeNode){ifroot==nil||k==0{return}dfs(root.Right)k--ifk==0{ans=root.Val}dfs(root.Left)}dfs(root)return}
/** * Definition for a binary tree node. * public class TreeNode { * public int val; * public TreeNode left; * public TreeNode right; * public TreeNode(int x) { val = x; } * } */publicclassSolution{privateintans;privateintk;publicintKthLargest(TreeNoderoot,intk){this.k=k;dfs(root);returnans;}privatevoiddfs(TreeNoderoot){if(root==null||k==0){return;}dfs(root.right);if(--k==0){ans=root.val;}dfs(root.left);}}
/* public class TreeNode {* public var val: Int* public var left: TreeNode?* public var right: TreeNode?* public init(_ val: Int) {* self.val = val* self.left = nil* self.right = nil* }* }*/classSolution{privatevark:Int=0privatevarans:Int=0funckthLargest(_root:TreeNode?,_k:Int)->Int{self.k=kdfs(root)returnans}privatefuncdfs(_root:TreeNode?){guardletroot=root,k>0else{return}dfs(root.right)k-=1ifk==0{ans=root.valreturn}dfs(root.left)}}