【剑指Offer54-二叉搜索树的第k大的节点(附带排序二叉树创建测试)】

题目:
在这里插入图片描述
很简单。反向中序遍历然后提前退出就可以得到答案了。
不过这道题我为了加深我非递归中序遍历的印象,使用了正向中序遍历迭代的方式:
C++代码附带测试:

#include<iostream>
#include<algorithm>
#include<vector>
#include<stack>

using namespace std;

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
 
struct TreeNode{
	int val;
	TreeNode *left;
	TreeNode *right;
	TreeNode(int x) : val(x),left(nullptr),right(nullptr){}
};

TreeNode* insert(TreeNode* root,int x){
	if(root==nullptr){
		root = new TreeNode(x);
		return root;
	}
	
	if(x>root->val){
		root->right = insert(root->right,x);
	}else{
		root->left = insert(root->left,x);
	}
	
	return root;
}


TreeNode* createTree(vector<int> arr){
	TreeNode *root = new TreeNode(arr[0]);
	for(int i=1;i<arr.size();i++){
		root = insert(root,arr[i]);
	}
	return root;
}


int inorder(TreeNode* root){
	TreeNode* p = root;
	stack<TreeNode*> store;
	
	while(!store.empty()||p){
		if(p){
			store.push(p);
			p = p->left;
		} 
		else{
			p = store.top();
			store.pop();
			cout<<p->val<<" ";
			p = p->right;
		}
	}
}

void reverseinorder(TreeNode* root){
	if(root==nullptr){
		return;
	}
	reverseinorder(root->right);
	cout<<root->val<<" ";
	reverseinorder(root->left);
}

class Solution {
public:
    int kthLargest(TreeNode* root, int k) {
		TreeNode* p = root;
		stack<TreeNode*> store;
		vector<int> sup;
		
		while(!store.empty()||p){
			if(p){
				store.push(p);
				p = p->left;
			}
			else{
				p = store.top();
				store.pop();
				sup.push_back(p->val);
				p = p->right;
			}
		}
		
		int n = sup.size();
		int ans = n - k;
		return sup[ans];
    }
};


int main(){
	vector<int> arr = {5,3,6,2,4,1};
	TreeNode* root = createTree(arr);
	inorder(root);
	cout<<endl;
	reverseinorder(root);
	Solution solution;
	cout<<solution.kthLargest(root,1)<<endl;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值