标签:
We essentailly do an in-order traversal (中序遍历) of the tree since the in-order traversal results in a sorted list of node items.
1 def traverse_binary_tree(node, callback): 2 if node is None: 3 return 4 traverse_binary_tree(node.leftChild, callback) 5 callback(node.value) 6 traverse_binary_tree(node.rightChild, callback)
But here, we should not use recursive (递归) since it will output the ordered list at one time. Alternatively, we interatively (迭代) output the next smallest element with the help of a Stack. In a binary search tree, we always has the value of left node < the value of parent node <= the value of the right node. Therefore, we iteratively visit the nodes on the left path of a given a starting node and push them into the stack. Everytime, we pop the smallest node n, and we need to push all the nodes on the left path starting from the right node of n, namely, n.right.
Take the following binary search tree as an example. We start from root node 8, we push 8, 3, 1 into the stack.
If we call hasNext(), we just need to check if the stack is empty or not.
If we call next(), we pop the top node in the stack, that is node 1. The nodes in the stack is 8, 3. We further check if node 1 has any right nodes since all its right nodes should be smaller than its parent node 3. Since node 1 does not have right nodes, the next smallest element is node 3.
Now if we call next(), we pop node 3. The stack contains 8. Since node 3 has right node, we then push all the nodes on the left path starting from node 6, that are 6 and 4. Now the stack includes 8, 6, 4. We can see we will always keep the smallest node on the top of the stack.
Initially, we push(8), push(3), push(1) --> 8, 3, 1, then for every next() cal, the status of the stack is:
pop(1) --> 8, 3
pop(3), push(6), push(4) --> 8, 6, 4
pop(4) --> 8, 6
pop(6), push(7) --> 8, 7
Here is java code:
1 /** 2 * Definition for binary tree 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 // we use a Stack to keep the 11 12 public class BSTIterator { 13 //Stack<TreeNode> s = new LinkedList<TreeNode>(); 14 Deque<TreeNode> s = new ArrayDeque<TreeNode>(); 15 public BSTIterator(TreeNode root) { 16 TreeNode n = root; 17 while(n!=null){ 18 s.push(n); 19 n = n.left; 20 } 21 } 22 23 /** @return whether we have a next smallest number */ 24 public boolean hasNext() { 25 if(s.isEmpty()) 26 return false; 27 return true; 28 } 29 30 /** @return the next smallest number */ 31 public int next() { 32 TreeNode n1 = s.pop(); 33 TreeNode l = n1.right; 34 while(l != null){ 35 s.push(l); 36 l = l.left; 37 } 38 return n1.val; 39 } 40 } 41 42 /** 43 * Your BSTIterator will be called like this: 44 * BSTIterator i = new BSTIterator(root); 45 * while (i.hasNext()) v[f()] = i.next(); 46 */
Leetcode: Binary Search Tree Iterator
标签:
原文地址:http://www.cnblogs.com/kezpitt/p/4300476.html