您的位置:首页 > 其它

230. Kth Smallest Element in a BST

2016-02-29 14:05 465 查看
Given a binary tree, return the inorder traversal of its nodes' values.

For example:

Given binary tree
{1,#,2,3}
,

1
\
2
/
3


return
[1,3,2]
.

solution:

/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
if(!root) return {};
vector<int> res;
stack<TreeNode *> stk;
while(root||!stk.empty()){
while(root){
stk.push(root);
root = root->left;
}
root = stk.top();
stk.pop();
res.push_back(root->val);
root = root->right;
}
return res;
}
};


心得:利用中序遍历

运行速度较快。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: