230. 二叉搜索树中第K小的元素
1 class Solution 2 { 3 public: 4 int kthSmallest(TreeNode* root, int k) 5 { 6 stack<TreeNode*> s; 7 TreeNode *cur = root; 8 while(!s.empty() || cur) 9 { 10 if(cur) 11 { 12 s.push(cur); 13 cur = cur->left; 14 } 15 else 16 { 17 cur = s.top(); 18 s.pop(); 19 k--; 20 if(0 == k) return cur->val; 21 cur = cur->right; 22 } 23 } 24 return 0; 25 } 26 };
1 // left = 左子树节点的个数 2 3 //1、if k <= left: return dfs(root->left,k); 4 //2、if k == left + 1: return root->val; 5 //3、if k > left + 1: return dfs(root->right,k - left - 1); 6 7 class Solution 8 { 9 public: 10 int kthSmallest(TreeNode* root, int k) 11 { 12 int left = findChild(root->left); 13 14 if(k <= left) return kthSmallest(root->left,k); 15 else if(k == left + 1) return root->val; 16 return kthSmallest(root->right,k - left - 1); 17 } 18 19 int findChild(TreeNode* root)//记录当前节点及其左右节点的个数 20 { 21 if(!root) return 0; 22 return findChild(root->left) + findChild(root->right) + 1; 23 } 24 };
Mamba never out

浙公网安备 33010602011771号