zoukankan      html  css  js  c++  java
  • LeetCode 230 Kth Smallest Element in a BST 二叉搜索树中的第K个元素

    1、非递归解法

     1 /**
     2  * Definition for a binary tree node.
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     int kthSmallest(TreeNode* root, int k) {
    13         if(root==nullptr)
    14             return -1;
    15         stack<TreeNode*> stk;
    16         while(root||!stk.empty())
    17         {
    18             if(root)
    19             {
    20                 stk.push(root);
    21                 root=root->left;
    22             }
    23             else
    24             {
    25                 root=stk.top();
    26                 stk.pop();
    27                 if(k==1)
    28                     return root->val;
    29                 --k;
    30                 root=root->right;
    31             }
    32         }
    33         return -1;
    34     }
    35 };

    2、递归解法

     1 /**
     2  * Definition for a binary tree node.
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     int kthSmallest(TreeNode* root, int k) {
    13         return helper(root, k);
    14     }
    15     int helper(TreeNode* root, int &k) {
    16         if (!root)
    17             return -1;
    18         int val = helper(root->left, k);
    19         if (k == 0)
    20             return val;
    21         if (--k == 0)
    22             return root->val;
    23         return helper(root->right, k);
    24     }
    25 };
  • 相关阅读:
    samba服务器之无认证进入共享目录
    中断
    html里<div> <br /> <p>三者区别
    块级元素和内联元素
    div和span标签
    django添加装饰器
    cookie和session
    Django报错:__init__() missing 1 required positional argument: 'on_delete'
    pycharm创建新django app
    djiango控制语句
  • 原文地址:https://www.cnblogs.com/xidian2014/p/8533095.html
Copyright © 2011-2022 走看看