/** * 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);}}
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */funckthLargest(root*TreeNode,kint)int{ch:=make(chanint)ctx,cancel:=context.WithCancel(context.Background())defercancel()goinorder(ctx,root,ch)for;k>1;k--{<-ch}return<-ch}funcinorder(ctxcontext.Context,cur*TreeNode,chchan<-int){ifcur!=nil{inorder(ctx,cur.Right,ch)select{casech<-cur.Val:case<-ctx.Done():return}inorder(ctx,cur.Left,ch)}}