0
点赞
收藏
分享

微信扫一扫

剑指offer 54. 二叉搜索树的第k大节点

yeamy 2022-04-16 阅读 45

剑指 Offer 54. 二叉搜索树的第k大节点 - 力扣(LeetCode) (leetcode-cn.com)

其实就是中序遍历

class Solution {
public:
	int kthLargest(TreeNode* root, int k) {
		int count = 0;
		stack<TreeNode*> nodeStack;
		while (root || !nodeStack.empty()) {
			while (root) {
				nodeStack.push(root);
				root = root->right;
			}
			if (!nodeStack.empty()) {
				root = nodeStack.top();	nodeStack.pop();
				if (++count == k) return root->val;
				root = root->left;
			}
		}
		return 0;
	}
};

 

举报

相关推荐

0 条评论