559 n叉树的最大深度
题目链接/文章讲解/视频讲解: https://programmercarl.com/0104.%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E6%9C%80%E5%A4%A7%E6%B7%B1%E5%BA%A6.html
思路:本题和之前的n叉树的层次遍历的基础上扩展,由于最大深度其实就是层次遍历输出的二维数组里一维数组的个数。
如[[1],[3,2,4],[5,6]],即最大深度应为arr.length = 3
/**
* // Definition for a Node.
* function Node(val,children) {
* this.val = val;
* this.children = children;
* };
*/
/**
* @param {Node|null} root
* @return {number}
*/
var maxDepth = function(root) {
if(root === null) return 0;
let res = [];
let queue = [root];
while(queue.length > 0){
let len = queue.length;
let subRes = [];
while(len){
let cur = queue.shift();
subRes.push(cur.val);
for(let item of cur.children){
queue.push(item);
}
len--;
}
res.push(subRes);
}
return res.length;
};
完全二叉树的节点个数
题目链接/文章讲解/视频讲解:https://programmercarl.com/0222.%E5%AE%8C%E5%85%A8%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E8%8A%82%E7%82%B9%E4%B8%AA%E6%95%B0.html
方法一:自己写的,很笨,还是基于BFS,每次往subRes里push的时候就count++
但没有用到完全二叉树的特性,感觉不太对
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var countNodes = function(root) {
if(root === null) return 0;
let res = [];
let queue = [root];
let count = 0;
while(queue.length > 0){
let len = queue.length;
let subRes = [];
while(len){
let cur = queue.shift();
subRes.push(cur.val);
count++;
if(cur.left) queue.push(cur.left);
if(cur.right) queue.push(cur.right);
len--;
}
res.push(subRes);
}
return count;
};
方法二:递归(依然是当成普通二叉树对待),后序遍历
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var countNodes = function(root) {
if(root === null) return 0;
let leftNum = countNodes(root.left);
let rightNum = countNodes(root.right);
result = leftNum + rightNum + 1;
return result;
};
方法三:基于完全二叉树和满二叉树的特质,采用递归(后序)
因为要分别计算一个节点左侧和右侧的深度,如果是完全二叉树则不用担心中间的节点不存在的情况。因此这种方法的时间复杂度不是O(n),因为中间的节点不会被遍历到,只会遍历两侧的节点。(详解看代码随想录视频)
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var countNodes = function(root) {
if(root === null) return 0;
//定义左右指针
let left = root.left;
let right = root.right;
let leftDepth = 0,rightDepth = 0;
while(left){
left = left.left;
leftDepth++;
}
while(right){
right = right.right;
rightDepth++;
}
//若向左和向右的深度是一样的,则为满二叉树
if(leftDepth === rightDepth){
return Math.pow(2, leftDepth+1) - 1;
}
return countNodes(root.left)+countNodes(root.right)+1;
};