[Random Coding] Tree Iterator

来源:互联网 发布:icloud照片下载到mac 编辑:程序博客网 时间:2024/05/02 04:55
package RandomPractice;import java.util.NoSuchElementException;import util.*;public class TreeIterator {private BTNode next;public TreeIterator(BTNode root){next = root;if(next == null)return;while(next.left != null)next = next.left;}public boolean hasNext(){return next != null;}public BTNode next(){if(!hasNext())throw new NoSuchElementException();BTNode result = next;if(next.right != null){next = next.right;while(next.left != null)next = next.left;} else{while(true){if(next.parent == null){next = null;break;} if(next.parent.left == next){next = next.parent;break;}next = next.parent;}}return result;}public static void main(String[] args){BTNode root = new BTNode(4);root.left = new BTNode(2);root.right = new BTNode(5);root.left.parent = root;root.right.parent = root;root.left.left = new BTNode(1);root.left.right = new BTNode(3);root.left.left.parent = root.left;root.left.right.parent = root.left;TreeIterator it = new TreeIterator(root);while(it.hasNext())System.out.println(it.next().value);}}

0 0