LeetCode 230 Kth Smallest Element in a BST 二叉搜索树中的第K个元素

1、非递归解法

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     int kthSmallest(TreeNode* root, int k) {
13         if(root==nullptr)
14             return -1;
15         stack<TreeNode*> stk;
16         while(root||!stk.empty())
17         {
18             if(root)
19             {
20                 stk.push(root);
21                 root=root->left;
22             }
23             else
24             {
25                 root=stk.top();
26                 stk.pop();
27                 if(k==1)
28                     return root->val;
29                 --k;
30                 root=root->right;
31             }
32         }
33         return -1;
34     }
35 };

2、递归解法

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     int kthSmallest(TreeNode* root, int k) {
13         return helper(root, k);
14     }
15     int helper(TreeNode* root, int &k) {
16         if (!root)
17             return -1;
18         int val = helper(root->left, k);
19         if (k == 0)
20             return val;
21         if (--k == 0)
22             return root->val;
23         return helper(root->right, k);
24     }
25 };

 

posted on 2018-03-09 12:00  lina2014  阅读(109)  评论(0编辑  收藏  举报

导航