码迷,mamicode.com
首页 > 其他好文 > 详细

Binary Search Tree Iterator

时间:2015-08-10 00:12:14      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace LeetCode
 8 {
 9     class BSTIterator
10     {
11         Stack<TreeNode> stack = new Stack<TreeNode>();
12         public BSTIterator (TreeNode root)
13         {
14             while (root!=null)
15             {
16                 stack.Push(root);
17                 root = root.left;
18             }
19         }
20 
21         public bool HasNext()
22         {
23             return stack.Count > 0;
24         }
25 
26         public int Next()
27         {
28             TreeNode node = stack.Pop();
29             int res = node.val;
30             if (node.right != null)
31             {
32                 node = node.right;
33                 while (node != null)
34                 {
35                     stack.Push(node);
36                     node = node.left;
37                 }
38             }
39             return res;
40         }
41     }
42 }

 

Binary Search Tree Iterator

标签:

原文地址:http://www.cnblogs.com/HuoAA/p/4716719.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!