Use two stacks to store the node for different directions.
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
Stack<TreeNode> s1 = new Stack<TreeNode>();
Stack<TreeNode> s2 = new Stack<TreeNode>();
if (root == null) return result;
else {
List<Integer> curr = new ArrayList<Integer>();
curr.add(root.val);
result.add(curr);
if (root.left != null)
s1.push(root.left);
if (root.right != null)
s1.push(root.right);
helper(result, s1, s2);
return result;
}
}
private void helper(List<List<Integer>> result, Stack<TreeNode> s1, Stack<TreeNode> s2) {
if (s1.empty() && s2.empty()) return;
List<Integer> tempList = new ArrayList<Integer>();
TreeNode tempNode = null;
if (!s1.empty()) {
while (!s1.empty()) {
tempNode = s1.pop();
tempList.add(tempNode.val);
if (tempNode.right != null) {
s2.push(tempNode.right);
}
if (tempNode.left != null) {
s2.push(tempNode.left);
}
}
} else {
while (!s2.empty()) {
tempNode = s2.pop();
tempList.add(tempNode.val);
if (tempNode.left != null) {
s1.push(tempNode.left);
}
if (tempNode.right != null) {
s1.push(tempNode.right);
}
}
}
result.add(tempList);
helper(result, s1, s2);
return;
}
No comments:
Post a Comment