Binary Tree Level Order Traversal
Given a binary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level).
For example:
Given binary tree [3,9,20,null,null,15,7],
return its level order traversal as:
1 2 3 4 5
| [ [3], [9,20], [15,7] ]
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
|
var levelOrder = function(root) { if (!root) return [];
var ans = [] , tmp = [root];
while (tmp.length) { var res = [] , a = [];
for (var i = 0, len = tmp.length; i < len; i++) { if (!tmp[i]) continue; res.push(tmp[i].val); a.push(tmp[i].left); a.push(tmp[i].right); }
tmp = a.concat(); if (res.length) ans.push(res); }
return ans; };
|
Binary Tree Level Order Traversal 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 [3,9,20,null,null,15,7],
return its bottom-up level order traversal as:
1 2 3 4 5
| [ [15,7], [9,20], [3] ]
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
|
var levelOrderBottom = function(root) { if (!root) return [];
var ans = [], tmp = [root];
while (tmp.length) { var res = [], _tmp = [];
tmp.forEach(function(item) { res.push(item.val); if (item.left) _tmp.push(item.left); if (item.right) _tmp.push(item.right); });
ans.push(res); tmp = _tmp; }
return ans.reverse();
};
|
Binary Tree Paths
Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
All root-to-leaf paths are:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
|
var ans, res;
function dfs(root) { if (!root) return;
res.push(root.val);
if (!root.left && !root.right) { var str = res.reduce(function(pre, item) { return pre + '->' + item; });
str = str.toString();
ans.push(str); res.pop(); return; }
if (root.left) dfs(root.left); if (root.right) dfs(root.right);
res.pop(); }
var binaryTreePaths = function(root) { ans = [], res = []; dfs(root); return ans; };
|