Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit04022c7

Browse files
author
applewjg
committed
Binary Search Tree Iterator
Change-Id: Id1401f7bbbb13cca87a42f24b4e317e669aebe87
1 parent553702e commit04022c7

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

‎BinarySearchTreeIterator.java

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
/*
2+
Author: king, wangjingui@outlook.com
3+
Date: Dec 31, 2014
4+
Problem: Binary Search Tree Iterator
5+
Difficulty: Easy
6+
Source: https://oj.leetcode.com/problems/binary-search-tree-iterator/
7+
Notes:
8+
Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.
9+
10+
Calling next() will return the next smallest number in the BST.
11+
12+
Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.
13+
14+
Solution: Inorder traversal.
15+
*/
16+
/**
17+
* Definition for binary tree
18+
* public class TreeNode {
19+
* int val;
20+
* TreeNode left;
21+
* TreeNode right;
22+
* TreeNode(int x) { val = x; }
23+
* }
24+
*/
25+
26+
publicclassBSTIterator {
27+
28+
publicBSTIterator(TreeNoderoot) {
29+
stk =newStack<TreeNode>();
30+
node =root;
31+
}
32+
33+
/** @return whether we have a next smallest number */
34+
publicbooleanhasNext() {
35+
if (stk.isEmpty() ==true &&node ==null)returnfalse;
36+
returntrue;
37+
}
38+
39+
/** @return the next smallest number */
40+
publicintnext() {
41+
if (stk.isEmpty() ==true &&node ==null)return0;
42+
while (node !=null) {
43+
stk.push(node);
44+
node =node.left;
45+
}
46+
intres =0;
47+
node =stk.pop();
48+
res =node.val;
49+
node =node.right;
50+
returnres;
51+
}
52+
privateStack<TreeNode>stk;
53+
privateTreeNodenode;
54+
}
55+
56+
/**
57+
* Your BSTIterator will be called like this:
58+
* BSTIterator i = new BSTIterator(root);
59+
* while (i.hasNext()) v[f()] = i.next();
60+
*/

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp