题目链接
法一(非递归中序遍历)
public class Solution173_1 {
private Deque<TreeNode> stack;
public Solution173_1(TreeNode root) {
this.stack = new LinkedList();
while (root != null) {
stack.push(root);
root = root.left;
}
}
public int next() {
TreeNode node = stack.pop();
int val = node.val;
node = node.right;
while (node != null) {
stack.push(node);
node = node.left;
}
return val;
}
public boolean hasNext() {
return !stack.isEmpty();
}
}
法二(直接dfs)
public class Solution173_2 {
private Iterator<Integer> iter;
public Solution173_2(TreeNode root) {
List<Integer> list = new LinkedList<>();
dfs(root, list);
iter = list.iterator();
}
private void dfs(TreeNode root, List<Integer> list) {
if (root == null) {
return;
}
dfs(root.left, list);
list.add(root.val);
dfs(root.right, list);
}
public int next() {
return iter.next();
}
public boolean hasNext() {
return iter.hasNext();
}
}
本地测试
lay.showTitle(173);
List<Integer> arr173 = Arrays.asList(7, 3, 15, null, null, 9, 20);
TreeNode root173 = treeOpt.createTreeByLayerOrder(arr173);
treeOpt.layerOrder(root173);
Solution173_1 sol173_1 = new Solution173_1(root173);
System.out.print(sol173_1.next() + " ");
System.out.print(sol173_1.next() + " ");
System.out.print(sol173_1.hasNext() + " ");
System.out.print(sol173_1.next() + " ");
System.out.print(sol173_1.hasNext() + " ");
System.out.print(sol173_1.next() + " ");
System.out.print(sol173_1.hasNext() + " ");
System.out.print(sol173_1.next() + " ");
System.out.println(sol173_1.hasNext());
Solution173_2 sol173_2 = new Solution173_2(root173);
System.out.print(sol173_2.next() + " ");
System.out.print(sol173_2.next() + " ");
System.out.print(sol173_2.hasNext() + " ");
System.out.print(sol173_2.next() + " ");
System.out.print(sol173_2.hasNext() + " ");
System.out.print(sol173_2.next() + " ");
System.out.print(sol173_2.hasNext() + " ");
System.out.print(sol173_2.next() + " ");
System.out.println(sol173_2.hasNext());