树操作-二叉树反转.js
/**
* 二叉树--先序遍历
* @description
* 给定一个二叉树,{"val":1,"left":null,"right":{"val":2,"left":{"val":3,"left":null,"right":null},"right":null}}
* 使用先序遍历,返回output数组 [1, 2, 3]
* @param {Object}
* @returns {Array} 遍历后结果
*/
// Answer
var preorderTraversal = function (root) {
var output = [];
var traversal = function (root) {
if (root.val) output.push(root.val);
if (root.left) traversal(root.left);
if (root.right) traversal(root.right);
};
traversal(root);
return output;
};
/**
* 二叉树反转
* @param {TreeNode} root
* @return {TreeNode}
*/
let root = {
val: 4,
left: {
val: 2,
left: {
val: 1,
left: null,
right: null,
},
right: {
val: 3,
left: null,
right: null,
},
},
right: {
val: 7,
left: {
val: 6,
left: null,
right: null,
},
right: {
val: 9,
left: null,
right: null,
},
},
};
var invertTree = function (root) {
if (!root) {
return root;
}
let val = root.right;
root.right = root.left;
root.left = val;
if (root.left) {
invertTree(root.left);
}
if (root.right) {
invertTree(root.right);
}
return root;
};
栈操作-括号匹配.js
// 判断字符串是否匹配
let arr = '[][]()({{}}'
数组扁平化
// 实现 Flat 函数,完成数组扁平化操作
var arr = [1,2,3,[4,5,[6,7],8],2,2]
nArr = []
function fn(arr) {
arr.forEach(node => {
if(typeof node == 'number') {
nArr.push(node)
} else {
fn(node)
}
});
}
fn(arr)
console.log(nArr);