leetcode 222 题 [medium]
中:完全二叉树的节点个数
英:Count Complete Tree Nodes
题解一:
使用DFS或BFS可以直接简单的解决这道题
-
实现:DFS + 优化(提前结束递归)
/** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } */ /** * @param {TreeNode} root * @return {number} */ var countNodes = function(root) { /** * DFS + 优化 * 时间复杂度:O(n) + 优化 * 空间复杂度: O(logn) 递归栈空间 */ // 预处理 if(!root) return 0; // 计算树高(完全二叉树,一直找左子节点,一定能到达最后一层) let height = 1; // 树高度 let node = root; while(node = node.left) height++; // DFS let bottomCount = 0; // 统计最后一层的结点数 let canStop = false; // 优化:当查询到最后一层结束,canStop设置为true,表明后续的递归无需再进行 function recurse(_root, _currHeight = 1