Binary Tree Postorder Traversal
Given a binary tree, return the postorder traversal of its nodes’ values.
For example:
Given binary tree [1,null,2,3]
return [3,2,1]
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
|
function dfs(root, ans) { if (!root) return;
dfs(root.left, ans); dfs(root.right, ans);
ans.push(root.val); }
var postorderTraversal = function(root) { var ans = []; dfs(root, ans); return ans; };
|
Binary Tree Preorder Traversal
Given a binary tree, return the preorder traversal of its nodes’ values.
For example:
Given binary tree [1,null,2,3]
return [1,2,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
|
function dfs(root, ans) { if (!root) return; ans.push(root.val);
dfs(root.left, ans); dfs(root.right, ans); }
var preorderTraversal = function(root) { var ans = []; dfs(root, ans); return ans; };
|
Binary Tree Right Side View
Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
For example:
Given the following binary tree,
1 2 3 4 5
| 1 <--- / \ 2 3 <--- \ \ 5 4 <---
|
You should return [1, 3, 4]
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
|
var rightSideView = 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); }
var a = []; ans.forEach(function(item) { a.push(item.pop()); });
return a; };
|