我尝试自己动手进行迭代后序遍历。我的解决方案在Leetcode Online Judge
中超出时间限制public List<Integer> postorderTraversalIterativel(TreeNode root) {
List<Integer> ret = new LinkedList<Integer>();
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode cur = root;
while (cur != null || !stack.isEmpty()) {
if (cur != null) {
stack.push(cur);
cur = cur.left;
} else {
TreeNode parent = stack.peek(), child = null;
if (parent.right == null) {
// pop hard
stack.pop();
while (parent.right == child && !stack.isEmpty()) {
child = parent;
ret.add(child.val);
parent = stack.pop();
}
} else {
cur = parent.right;
}
}
}
return ret;
}
虽然wikipedia的官方实施可以通过测试。
public List<Integer> postorderTraversalIterativel(TreeNode root) {
List<Integer> ret = new LinkedList<Integer>();
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode cur = root, lastVisited = null;
while (cur != null || !stack.isEmpty()) {
if (cur != null) {
stack.push(cur);
cur = cur.left;
} else {
TreeNode parent = stack.peek();
if (parent.right != null && lastVisited != parent.right) {
// make sure pop all the node has right child of the
// previous pop
cur = parent.right;
} else {
stack.pop();
ret.add(parent.val);
lastVisited = parent;
}
}
}
return ret;
}
通过检查代码,我无法理解为什么我的实现比官方实现慢。谁能指出发生了什么? (可能我的解决方案在逻辑上是错误的,但是我的解决方案失败了,我已经进行了单元测试,单元测试很快就完成了......)。欢迎提出任何意见。
public void testPostorderTraversal1() {
TreeNode root = new TreeNode(3);
TreeNode right = new TreeNode(1);
TreeNode rightLeft = new TreeNode(2);
root.right = right;
right.left = rightLeft;
List<Integer> list = new LinkedList<Integer>();
list.add(2);
list.add(1);
list.add(3);
assertEquals(list.toString(), sut.postorderTraversal(root).toString());
}
public void testPostorderTraversal2() {
TreeNode root = new TreeNode(1);
TreeNode right = new TreeNode(2);
root.right = right;
List<Integer> list = new LinkedList<Integer>();
list.add(2);
list.add(1);
assertEquals(list.toString(), sut.postorderTraversal(root).toString());
}
答案 0 :(得分:1)
您的代码可以执行无限循环。
你的'testPostorderTraversal1'unitest没有完成。
如果有任何节点具有已离开子节点的右子节点,则无法完成。