230. Kth Smallest Element in a BST
来源:互联网 发布:mac系统如何下载软件 编辑:程序博客网 时间:2024/06/07 21:57
/*Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.Note: You may assume k is always valid, 1 ≤ k ≤ BST's total elements.Follow up:What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine?BST的中序遍历为升序,找到第k个节点即可*//** * 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: int kthSmallest(TreeNode* root, int k) { int cnt=k; int target; inorder(root,cnt,target); return target; } void inorder(TreeNode* root,int &k,int &target) { if(!root)return; if(root->left)inorder(root->left,k); k--; if(k==0){ target=root->val; return; } inorder(root->right,k); }};
阅读全文
0 0
- 230.Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 230. Kth Smallest Element in a BST
- 顺时针打印矩阵
- LintCode 647 Substring Anagrams
- Linux常用命令(1)
- Python IO笔记
- ArrayList源码学习
- 230. Kth Smallest Element in a BST
- 计算机组成原理与系统结构 第一章计算机概述
- Qt5开发学习之事件(十三)
- 《C++ Concurrency in Action》笔记4 hardware_concurrency()
- Linux系统下FTP服务器的搭建
- 九度题目1156:谁是你的潜在朋友
- android实现和web一样的圆角
- 无限轮播+GridView
- Handler机制