这种题目 和 索引数组一样麻烦,很容易被绕晕了。
987. 二叉树的垂序遍历
这样的 map
代码实现
var verticalTraversal = function(root) {let map = new Map();let res = [];const dfs = (node, row, col) => {if(node == null) return 0;map.set(col, [{val: node.val,row: row}, ...(map.get(col) || [])] )dfs(node.left, row + 1, col - 1);dfs(node.right, row + 1, col + 1);}dfs(root, 0, 0);for(let [key, values] of map.entries() ) {values.sort((a, b) => {if(a.row == b.row) {return a.val - b.val}return a.row - b.row;})if(key >= 0) {res.push(values.map(item => item.val))} else {res.unshift(values.map(item => item.val))}}return res;};
1) 要按照, map key 来排序:
而本题的插入正好是有序的,因此不需要排序 key
2)先按 row 排序,如果 row 相等,则按 value 排序。代码里正好倒着写。
- 比较模型:
[row, col, val]
垂序遍历:
- col
- row
val
res.sort((a, b) => {if (a[1] !== b[1]) {return a[1] - b[1];} else if (a[0] !== b[0]) {return a[0] - b[0];} else {return a[2] - b[2];}});
合并同列项:这个技法很牛逼,如何在遍历的过程中合并key相同的元素
const ans = [];let lastcol = -Number.MAX_VALUE;for (const tuple of nodes) {let [row, col, value] = tuple;if (col !== lastcol) {lastcol = col;ans.push([]);}ans[ans.length - 1].push(value);}return ans;
完整代码: ```javascript var verticalTraversal = function(root) { const nodes = []; dfs(root, 0, 0, nodes); nodes.sort((tuple1, tuple2) => {
if (tuple1[0] !== tuple2[0]) {return tuple1[0] - tuple2[0];} else if (tuple1[1] !== tuple2[1]) {return tuple1[1] - tuple2[1];} else {return tuple1[2] - tuple2[2];}
});
const ans = []; let lastcol = -Number.MAX_VALUE; for (const tuple of nodes) { let [row, col, value] = tuple;
if (col !== lastcol) {lastcol = col;ans.push([]);}ans[ans.length - 1].push(value);
} return ans; }
const dfs = (node, row, col, nodes) => { if (node === null) { return; } nodes.push([col, row, node.val]); dfs(node.left, row + 1, col - 1, nodes); dfs(node.right, row + 1, col + 1, nodes); }
2.双层map 递归 sort```javascriptvar verticalTraversal = function(root) {let map = new Map()function dfs(root, row, col) {if (!root) returnif (!map.has(col)) {map.set(col, new Map())}const item = map.get(col)if (!item.has(row)) {item.set(row, [])}item.get(row).push(root.val)dfs(root.left, row + 1, col - 1)dfs(root.right, row + 1, col + 1)}dfs(root, 0, 0)let arr = []for (let col of map) {arr.push(col)}return arr.sort((a, b) => a[0] - b[0]).map(item => {const arr = []for (let row of item[1]) {arr.push(row)}arr.sort((a, b) => a[0] - b[0])return arr.map(it => {if (it[1].length > 1) { // 这里排序的特殊之处it[1].sort((a, b) => a - b)}return it[1]}).flat()})};
314. 二叉树的垂直遍历
和 987 相同题目,还更简单
