62二叉搜索树的第k个结点
题目描述
给定一颗二叉搜索树,请找出其中的第k大的结点。例如, 5 / \ 3 7 /\ /\ 2 4 6 8 中,按结点数值大小顺序第三个结点的值为4。
思路
二叉搜索树的中序遍历的输出结果是拍好序的,直接输出第K个即可
1 public class Solution { 2 int time = 0; 3 TreeNode KthNode(TreeNode root, int k){ 4 if(root==null) return null; 5 TreeNode node = KthNode(root.left,k); 6 if(node!=null) return node; 7 time++; 8 if(time==k) 9 return root; 10 node = KthNode(root.right,k); 11 return node; 12 13 } 14 15 }
20180321
1 public class Solution { 2 int time = 0; 3 TreeNode res ; 4 TreeNode KthNode(TreeNode root, int k) 5 { 6 help(root,k); 7 return res; 8 } 9 private void help(TreeNode root,int k){ 10 if(root==null) 11 return ; 12 help(root.left,k); 13 time++; 14 if(time ==k) 15 res = root; 16 help(root.right,k); 17 } 18 }
c++:20180731
1 /* 2 struct TreeNode { 3 int val; 4 struct TreeNode *left; 5 struct TreeNode *right; 6 TreeNode(int x) : 7 val(x), left(NULL), right(NULL) { 8 } 9 }; 10 */ 11 class Solution { 12 13 public: 14 TreeNode* KthNode(TreeNode* root, int k) 15 { 16 int cnt = 0; 17 stack<TreeNode*> s ; 18 while(root!=NULL ||!s.empty()){ 19 while(root!=NULL){ 20 s.push(root); 21 root = root->left; 22 } 23 if(!s.empty()){ 24 root = s.top(); 25 s.pop(); 26 cnt++; 27 if(cnt==k) return root; 28 root = root->right; 29 } 30 } 31 return NULL; 32 } 33 34 };