Node k-th largest face questions 54. leetcode-- binary search tree

K-th largest face questions node 54. The binary search tree
given a binary search tree, please find out the k-th largest nodes.

Example:

Input: root = [5,3,6,2,4, null, null, 1], k = 3 Output: 4
Input: root = [3,1,4, null, 2], k = 1 Output: 4

      5
     / \
    3   6
   / \
  2   4
 /
1


 3
/ \
1   4
 \
  2

limit:

1 ≤ k ≤ number of the binary search tree element

A thought: non-recursive

/**
 * 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 kthLargest(TreeNode* root, int k) {
        stack<TreeNode*> stack;
        //vector<int> nums;
        int n = 0;
        TreeNode* p = root;
        while (p || !stack.empty()){
            while (p){
                stack.push(p);
                p = p->right;
            }
            p = stack.top();
            stack.pop();
            //nums.push_back(p->val);
            n++;
            if (n == k){
                return p->val;
            }
            p = p->left;
        }
        return 0;
    }
};
/*20ms,26.6MB*/

Ideas II: recursive

class Solution {
private:
    int ans = 0;
    int n = 0;
public:
    int kthLargest(TreeNode* root, int k) {
        InOrderTraverse(root, k);
        return ans;
    }
    void InOrderTraverse(TreeNode* root, int k){
        if (root == NULL){
            return;
        }
        InOrderTraverse(root->right, k);
        n++;
        if (n == k){
            ans = root->val;
            return;
        }
        InOrderTraverse(root->left, k);
        return;
    }
};
/*16ms,26.8MB*/
Published 12 original articles · won praise 0 · Views 118

Guess you like

Origin blog.csdn.net/u011861832/article/details/104495005