zoukankan      html  css  js  c++  java
  • 二叉树中第 K小的元素

    给定一个二叉搜索树,编写一个函数 kthSmallest 来查找其中第 k 个最小的元素。

    说明:
    你可以假设 k 总是有效的,1 ≤ k ≤ 二叉搜索树元素个数。

    思路: 二叉搜索树因其有序,故采用中序遍历,可以得到第K小的元素。

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        int kthSmallest(TreeNode* root, int k) {
            int index = k;
            int kth = 0;
            TreeNode* find = findKth(root, index, kth);
            if(find) return find->val;
            return -1;
        }
        TreeNode* findKth(TreeNode* root, int index, int &k){
            if(root == NULL) {
                return NULL;
            }
            //左子树<根节点<右子树
            TreeNode* left = findKth(root->left,index, k);
            if(left) return left;
            k = k+1;
            if(k == index){  
               // cout << root->val << ",";
                return root;
            } 
            TreeNode* right = findKth(root->right, index, k);
            if(right) return right;
            else return NULL;        
            //return right? right:left;
        }
            
        
    };
    The Safest Way to Get what you Want is to Try and Deserve What you Want.
  • 相关阅读:
    elipse图标注解
    Thrift源码解析--transport
    IDL和生成代码分析
    thrift概述
    less分页阅读
    this与super使用总结(java)
    more分页阅读
    Arrays
    Teigha克隆db的blockTableRecord里面的一个实体
    Teigha的BlockTableRecord获取方法
  • 原文地址:https://www.cnblogs.com/Shinered/p/11498510.html
Copyright © 2011-2022 走看看