【二叉树】BST第K小值【230. Kth Smallest Element in a BST】

来源:互联网 发布:幻想神域攻略软件 编辑:程序博客网 时间:2024/06/06 07:23

题目链接:https://leetcode.com/problems/kth-smallest-element-in-a-bst/#/discuss

/** * 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) {        return getOrder(root,k);    }    //  中序遍历    int getOrder(TreeNode* root,int& k){        if(root){            int t=getOrder(root->left,k);            if(!k) return t;            k--;            if(k) t=getOrder(root->right,k);            else t=root->val;            return t;        }        return -1;    }};


阅读全文
0 0
原创粉丝点击