Skip to content

Commit

Permalink
Java solution 103 && 144
Browse files Browse the repository at this point in the history
  • Loading branch information
gavinfish committed Jun 8, 2017
1 parent a4d7a0f commit b3c8c19
Show file tree
Hide file tree
Showing 2 changed files with 92 additions and 0 deletions.
57 changes: 57 additions & 0 deletions java/_103BinaryTreeZigzagLevelOrderTraversal.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
* Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).
* <p>
* For example:
* Given binary tree [3,9,20,null,null,15,7],
* 3
* / \
* 9 20
* / \
* 15 7
* return its zigzag level order traversal as:
* [
* [3],
* [20,9],
* [15,7]
* ]
* <p>
* Created by drfish on 6/7/2017.
*/
public class _103BinaryTreeZigzagLevelOrderTraversal {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<>();
List<TreeNode> curr = new ArrayList<>();
boolean isOdd = true;

if (root == null) {
return result;
}
curr.add(root);

while (!curr.isEmpty()) {
List<TreeNode> next = new ArrayList<>();
List<Integer> level = new LinkedList<>();
for (TreeNode node : curr) {
if (node.left != null) {
next.add(node.left);
}
if (node.right != null) {
next.add(node.right);
}
if (isOdd) {
level.add(node.val);
} else {
level.add(0, node.val);
}
}
isOdd = !isOdd;
result.add(level);
curr = next;
}
return result;
}
}
35 changes: 35 additions & 0 deletions java/_144BinaryTreePreorderTraversal.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
* Given a binary tree, return the preorder traversal of its nodes' values.
* <p>
* For example:
* Given binary tree {1,#,2,3},
* 1
* \
* 2
* /
* 3
* return [1,2,3].
* <p>
* Note: Recursive solution is trivial, could you do it iteratively?
* Created by drfish on 6/8/2017.
*/
public class _144BinaryTreePreorderTraversal {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
while (root != null || !stack.isEmpty()) {
while (root != null) {
result.add(root.val);
stack.push(root);
root = root.left;
}
root = stack.pop();
root = root.right;
}
return result;
}
}

0 comments on commit b3c8c19

Please sign in to comment.