zoukankan      html  css  js  c++  java
  • Kth Smallest Element in a BST

    基本思想就是:二叉树的中序非递归遍历

     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         stack<TreeNode *> st;
    14         TreeNode * temp=root;
    15         int res;
    16         int count=0;
    17         if(root==NULL)
    18             return 0;
    19         while(temp!=NULL||!st.empty())
    20         {
    21             if(temp!=NULL)
    22             {
    23                 st.push(temp);
    24                 if(temp->left!=NULL)
    25                     temp=temp->left;
    26                 else
    27                     temp=NULL;
    28             }
    29             else if(!st.empty())
    30             {
    31                 temp=st.top();
    32                 st.pop();
    33                 count++;
    34                 if(count==k)
    35                 {
    36                     res=temp->val;
    37                     break;
    38                 }
    39                 temp=temp->right;
    40             }
    41         
    42         }
    43         return res;
    44     }
    45     
    46 };
  • 相关阅读:
    XP显示桌面
    批量改名
    poj 3126 BFS
    poj 3278 BFS
    poj 1426 BFS
    准备打酱油…
    POJ 2243 BFS 和 简单的调试方法学习
    K
    EXCEL fundamentals
    poj 1011 DFS+剪枝
  • 原文地址:https://www.cnblogs.com/aguai1992/p/4625807.html
Copyright © 2011-2022 走看看