给定一颗二叉搜索树,请找出其中的第k小的结点。例如, 5 / \ 3 7 /\ /\ 2 4 6 8 中,按结点数值大小顺序第三个结点的值为4。...

// ConsoleApplication2.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include "stdafx.h"
#include<iostream>
#include<vector>
#include<algorithm>
#include<numeric>
#include<list>
#include<iterator>
#include<queue>
#include<stack>
#include<algorithm>
using namespace std;





struct TreeNode {
    char val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
    val(x), left(NULL), right(NULL) {
    }
};
class Solution {
public:
    TreeNode* KthNode(TreeNode* pRoot, unsigned int k)
    {
        getData(pRoot);
        if (k <= 0) return NULL;
        if (k > qu.size()) return NULL;
        for (int i = 1; i < k; i++)
        {
            qu.pop();
        }
        return qu.front();
    }

    queue<TreeNode*> qu;
    void getData(TreeNode* T)
    {
        if (T == NULL) return;
        else
        {   
            getData(T->left);
            qu.push(T);
            getData(T->right);
        }
    }

    //序列化二叉树,前序创建二叉树
    int p = -1;
    TreeNode* Deserialize(char *str) {
        if (*str == NULL) return NULL; //str为空
        TreeNode *T = NULL;
        ++p;
        if (p >= strlen(str)) return NULL; //超出str的范围
        if (str[p] == '#') return NULL; //str的值等于#
        T = new TreeNode(str[p]);
        T->left = Deserialize(str);
        T->right = Deserialize(str);
        return T;
    }
    void preOrder(TreeNode *T)
    {
        if (T == NULL) return;
        else
        {
            cout << T->val << "  ";
            preOrder(T->left);
            preOrder(T->right);
        }
    }

};

int main()
{

    //int num = 5;
    //char *ch = new char[num];
    //cout << "strlen(ch):" << strlen(ch)<<endl;
    //cout << endl;


    Solution so;
    TreeNode *T;
    int num = 5;
    char *str = "532##4##76##8##";
    T = so.Deserialize(str);
    cout << "创建二叉树成功!"<<endl;

    cout << "前序遍历二叉树:" << endl;
    so.preOrder(T);
    cout << endl;

    TreeNode *re = so.KthNode(T,8);
    cout << "result:" << re->val << endl;


    //so.getData(T);
    //cout << "qu 队列中的值:" << endl;
    //so.print();
    //cout << endl;


    return 0;
}

转载于:https://www.cnblogs.com/wdan2016/p/6000152.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值