//-------------------------------------------树的遍历-------------------------------------------------
/**深度遍历之 先序遍历:根左右
* 深度遍历之 中序遍历:
* 深度遍历之 后序遍历:左右根
*/
//二叉树先序遍历 递归法
let resultArr = [];
let dfs = function (node) {
if (node) {
resultArr.push(node.val);//根
dfs(node.left); //左
dfs(node.right); //右
}
}
//二叉树先序遍历 迭代法
dfs = function (nodes) {
if (root == null) {
return []
}
let resultArr = [];
let stack = [nodes];
while (stack.length) {
let node = stack.pop(); // 取的是栈中最后一个j
resultArr.push(node.value);
if (node.right) stack.push(node.right); // 先压入右子树
if (node.left) stack.push(node.left); // 后压入左子树
}
return resultArr;
}
//n叉树先序遍历 递归法
var preorder = function (root) {
let resultArr = []
function qianxubianli(root) {
if (root) {
resultArr.push(root.val)
if (root.children) {
root.children.forEach(item => {
qianxubianli(item)
})
}
}
}
qianxubianli(root)
return resultArr
};
//n叉树先序遍历 迭代法
var preorder = function (root) {
if (root == null) {
return []
}
let resultArr = []
let stack = [root]
while (stack.length) {
let node = stack.pop()
resultArr.push(node.val)
if (node.children) {
stack.push(...node.children.reverse())//反向进栈
}
}
return resultArr
};
//n叉树后序遍历 递归法
var postorder = function (root) {
const res = []
function traversal(root) {
if (root) {
root.children.forEach(child => {//一直找最左叶子节点,没有了就把当前节点push进数组
traversal(child)
})
res.push(root.val)
}
}
traversal(root)
return res
}
//n叉树后序遍历 迭代法
var postorder = function (root) {
if (!root) return []
const ans = []
const stack = [root]
while (stack.length) {
const node = stack.pop()
ans.unshift(node.val)//!!
node.children && stack.push(...node.children)//!!
}
return ans
}
//-------------------------------------------树的最大深度-------------------------------------------------
//广度优先遍历,一直会遍历到最底层,
var maxDepth = function (root) {
if (root == null) {
return 0
}
let queue = [root]
let maxDepthNum = 0
while (queue.length) {
maxDepthNum++
let cacheNextLevelArr = []
//一层一层的进和出,方便计算层数
while (queue.length) {
let cur = queue.shift()
if (cur.children && cur.children.length) {
cacheNextLevelArr.push(...cur.children)
}
}
queue.push(...cacheNextLevelArr)
}
return maxDepthNum
};
//采用深度优先算法,递归计算除根节点外,每个子节点 node 的最大高度 max = Math.max(max, childNodeDepth),最后返回最大高度 max + 1 即可, 加 1 是加上根节点 root 的高度。
var maxDepth = function (root) {
if (!root) return 0
let max = 0
root.children && root.children.forEach(node => {
let temp = maxDepth(node)
max = max > temp ? max : temp//不断更新同一层级节点的最大值
// max = Math.max(max, maxDepth(node))
})
return max + 1//每走一次该函数,说明层次+1了
}
//深度遍历
// 计算每个树节点的叶子节点数量 递归
var getLeafCountTree = function (treeData, nodeLevel = 1) {
if (treeData.children == null || treeData.children.length == 0) {
treeData.tailNodeCount = 1;
treeData.nodeLevel = nodeLevel
return 1
}
var leafCount = 0;
nodeLevel++;
treeData.forEach(node => {
//一个节点的叶节点数量是它每个子节点叶节点数量之和
leaf += getLeafCountTree(node, nodeLevel)
})
nodeLevel--;//?????
treeData.tailNodeCount = leafCount
return leafCount
}