102.107. Binary Tree Level Order Traversal I&II
Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).
For example:
Given binary tree
Given binary tree
[3,9,20,null,null,15,7]
,3 / \ 9 20 / \ 15 7
102. return its level order traversal as:
[ [3], [9,20], [15,7] ]
107. return its bottom-up level order traversal as:
[ [15,7], [9,20], [3] ]
思路: BFS Using Queue, key is to track current level by queue.size()
Complexity: O(N) visit every node only once.
public List<List<Integer>> levelOrder(TreeNode root) { List<List<Integer>> res = new ArrayList<List<Integer>> (); if(root == null)return res; Queue<TreeNode> queue = new LinkedList<TreeNode>(); queue.add(root); while(!queue.isEmpty()){ int size = queue.size(); ArrayList<Integer> level = new ArrayList<Integer>(); for (int i = 0; i < size; i++){ TreeNode curr = queue.remove(); level.add(curr.val); if(curr.left != null) queue.add(curr.left); if(curr.right != null) queue.add(curr.right); } res.add(level);//res.add(0,level);--bottom up } return res; }
No comments:
Post a Comment