zoukankan      html  css  js  c++  java
  • 剑指Offer-- 二叉搜索树的第K个结点

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

    /*
    struct TreeNode {
        int val;
        struct TreeNode *left;
        struct TreeNode *right;
        TreeNode(int x) :
                val(x), left(NULL), right(NULL) {
        }
    };
    */
    class Solution {
    public:
        TreeNode* KthNode(TreeNode* pRoot, int k)
        {
            TreeNode* res = NULL;
            if (pRoot == NULL || k <= 0){
                return res;
            }
            int count = 0;
            return InOrderTraverse(pRoot, k, count);     //注意引用的时候必须是变量
        }
    
        TreeNode* InOrderTraverse(TreeNode* pRoot, int k,int& count){
            TreeNode* res = NULL;
            if (pRoot->left != NULL){
                 res = InOrderTraverse(pRoot->left, k, count);
            }
            
            
            if (res == NULL){            // 每一个结点的时候都要区判断是否已经查找到目标结点,这里用res不为空代表已经找到目标结点
                count++;                // count 用来标识 每次遍历一个结点,就会加1,若等于K就说明找到目标结点
                if (count == k){
                    res = pRoot;
                }
            }
            
            if (pRoot->right != NULL && res == NULL){    //当右子树不为空 并且 还没有找到目标结点的时候才会遍历右子树
                 res = InOrderTraverse(pRoot->right, k, count);
            }
            return res;
        }
    };
  • 相关阅读:
    JS定时执行,循环执行
    Ecshop(二次开发)
    百度歌曲接口
    给大家讲讲在哪些地方发外链最好
    360浏览器默认以兼容模式或急速模式方式打开页面
    子iframe 怎么调用 父级的JS函数
    ASP 发送邮件
    PHP发送邮件
    php表单数据验证类
    js获取url传递参数
  • 原文地址:https://www.cnblogs.com/simplepaul/p/7168597.html
Copyright © 2011-2022 走看看