一、二叉树层级遍历
// 初始化二叉树
function TreeNode(val){
this.val = val;
this.left = this.right =null;
}
function levelOrder(root) {
var res = [];
if(!root) return res;
recusion(root,0);
return res;
function recusion(root,level) {
if(!root) return;
// 判断当前level层是否已存在元素
if(res[level]){
res[level].push(root.val);
} else {
res[level] = [root.val];
}
if(root.left){
recusion(root.left,level+1);
}
if(root.right){
recusion(root.right,level+1);
}
}
}
二、求二叉树最大深度
// 初始化二叉树
function TreeNode(val){
this.val = val;
this.left = this.right =null;
}
function maxDepth(root) {
if(root === null){
return 0;
} else {
var leftDepth = maxDepth(root.left);
var rightDepth = maxDepth(root.right);
var childDepth = leftDepth>rightDepth?leftDepth:rightDepth;
return childDepth+1;
}
}
三、求二叉树的最大宽度
// 初始化二叉树
function TreeNode(val){
this.val = val;
this.left = this.right =null;
}
function maxWidth(root) {
if(!root) return 0;
var res = [],maxWidth = 1;
recusion(root,0,0);
return maxWidth;
function recusion(root,level,num) {
if(res[level]){
res[level].push(num);
} else{
res[level] = [num];
}
var tempArr = res[level];
var tempWidth = tempArr[tempArr.length-1]-tempArr[0]+1;
if(tempWidth>maxWidth){
maxWidth = tempWidth;
}
if(root.left){
recusion(root.left,level+1,num*2+1);
}
if(root.right){
recusion(root.right,level+1,num*2+2);
}
}
}
四、二叉树后续遍历
// 初始化二叉树
function TreeNode(val){
this.val = val;
this.left = this.right =null;
}
// 后续遍历 先子节点,在右子节点,在根节点
// 中序遍历 左-根-右
// 前序遍历 根-左-右
function postorderTraversal(root) {
var res = [];
if(!root) return res;
recusion(root);
return res;
function recusion(root) {
if(!root) return;
recusion(root.left);
recusion(root.right);
recusion(root.val);
}
}