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;
        }
    };
  • 相关阅读:
    面试题链接
    75 道 BAJT 高级 Java 面试题,你能答上几道?
    使用UML描述需求都实现的过程
    java面试题(下)
    golang中goconfig包使用解析
    golang中sublime text中配置goimports
    golang中new和make区别
    golang中并发sync和channel
    使用go build 进行条件编译
    golang中time包用法
  • 原文地址:https://www.cnblogs.com/simplepaul/p/7168597.html
Copyright © 2011-2022 走看看