Kth Smallest Element in a BST
2016-02-28 22:43
393 查看
题目:
Given a binary search tree, write a function
Note:
You may assume k is always valid, 1 ≤ k ≤ BST's total elements.
cpp:
方法一:递归
方法2:栈
Given a binary search tree, write a function
kthSmallestto find the kth smallest element in it.
Note:
You may assume k is always valid, 1 ≤ k ≤ BST's total elements.
cpp:
方法一:递归
class Solution { public: int kthSmallest(TreeNode* root,int k){ int result; inOrder(root,k,result); return result; } int n =0; void inOrder(TreeNode* root,int kth,int& kthVal){ if(!root ) return; inOrder(root->left,kth,kthVal); n = n + 1; if(n == kth) { kthVal = root->val; return; } inOrder(root->right,kth,kthVal); } };
方法2:栈
class Solution{ public: int kthSmallest(TreeNode* root,int k){ stack<TreeNode*> stack; int result; TreeNode *cur = root; while(!stack.empty() || cur){ if(cur){ stack.push(cur); cur = cur->left; }else{ TreeNode* temp = stack.top(); stack.pop(); k--; if(k==0) { result = temp->val; return result; } cur = temp->right; } } return result; } };
相关文章推荐
- Spiral Matrix
- 10. Regular Expression Matching-hard
- Password Validation using regular expressions(JavaScript)
- 数据包解析(基于wireshark)——物理层Frame
- PL/SQL之函数处理
- 字符集和编码
- 【CodeForces 520E】Pluses everywhere
- Java的Calendar使用
- VM虚拟机centos中的网络站点、主机访问
- java.lang.NoSuchFieldError: android.support.v7.appcompat.R$styleable.Theme_w的解决办法
- hdu 1063 Exponentiation/poj 1001
- FFmpeg获取视频的旋转角度rotate函数,一定能获取!(要放在解析视频流的时候才能获取)
- JavaScript 定义类或对象
- HDU 1596 也是最小路径Dijkstra
- 3-8-循环队列-栈和队列-第3章-《数据结构》课本源码-严蔚敏吴伟民版
- web前端排版
- GitHub教程
- android第三方登录数据库设计以及业务数据流向说明
- 静态数据的初始化
- Java冒泡排序和二分查找(预习)