Binary Search Tree Iterator Solutions in Java
Number 173
Difficulty Medium
Acceptance 56.7%
Link LeetCode
Solutions
Java solution by haoel/leetcode
// Source : https://oj.leetcode.com/problems/balanced-binary-tree/// Inspired by : http://www.jiuzhang.com/solutions/binary-search-tree-iterator/// Author : Lei Cao// Date : 2015-10-07package binarySearchTreeIterator;import java.util.Stack;/*** Definition of TreeNode:* public class TreeNode {* public int val;* public TreeNode left, right;* public TreeNode(int val) {* this.val = val;* this.left = this.right = null;* }* }* Example of iterate a tree:* Solution iterator = new Solution(root);* while (iterator.hasNext()) {* TreeNode node = iterator.next();* do something for node* }*/public class binarySearchTreeIterator {private TreeNode currentNode = null;private Stack<TreeNode> stack = new Stack<TreeNode>();//@param root: The root of binary tree.public binarySearchTreeIterator(TreeNode root) {if (root != null) {currentNode = root;}}//@return: True if there has next node, or falsepublic boolean hasNext() {// write your code herereturn currentNode != null || !stack.isEmpty();}//@return: return next nodepublic TreeNode next() {// write your code herewhile (currentNode != null) {stack.push(currentNode);currentNode = currentNode.left;}currentNode = stack.pop();TreeNode node = currentNode;currentNode = currentNode.right;return node;}}