(48) ~[222] 完全二叉树的节点个数

101 阅读1分钟

这个题,肯定要首先知道什么是完全二叉树,然后看了解析有n中,比较高校的应该是二分查找结合的,目前水平有限,看得不太明白,就找了2个最基本的 好理解的

var countNodes = function (root) {
	// 方法一 遍历二叉树
	/* if (!root) {
		return null;
	}
	const stack = [];
	stack.push(root);
	let num = 0;
	while (stack.length) {
		const top = stack.shift();
		num++;
		top.left && (stack.push(top.left));
		top.right && (stack.push(top.right));
	}
	return num; */
	// 方法二 递归
	return root ? countNodes(root.left) + countNodes(root.right) + 1 : null;

};

力扣本题传送