Created
August 10, 2019 08:00
-
-
Save shharma-vipin/9d27c6a06e9efc05390e331211149e94 to your computer and use it in GitHub Desktop.
ZigZag Traversal Of Binary Tree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public ArrayList<ArrayList<Integer>> zigzagLevelOrder(TreeNode A) { | |
Queue<TreeNode> q = new LinkedList<>(); | |
if(A == null) return null; | |
Stack<TreeNode> currentLevel = new Stack<>(); | |
Stack<TreeNode> nextLevel = new Stack<>(); | |
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>(); | |
currentLevel.push(A); | |
boolean ltr = true; | |
ArrayList<Integer> tempList = null; | |
while(!currentLevel.isEmpty()){ | |
TreeNode temp = currentLevel.pop(); | |
q.add(temp); | |
if(ltr){ | |
if(temp.left != null){ | |
nextLevel.push(temp.left); | |
} | |
if(temp.right != null){ | |
nextLevel.push(temp.right); | |
} | |
}else{ | |
if(temp.right != null){ | |
nextLevel.push(temp.right); | |
} | |
if(temp.left != null){ | |
nextLevel.push(temp.left); | |
} | |
} | |
if(currentLevel.isEmpty()){ | |
ltr = !ltr; | |
Stack<TreeNode> te = currentLevel; | |
currentLevel = nextLevel; | |
nextLevel = te; | |
tempList = new ArrayList<Integer>(); | |
while(!q.isEmpty()){ | |
tempList.add(q.remove().val); | |
} | |
result.add(tempList); | |
} | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment