We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
给出一个 完全二叉树,求出该树的节点个数。
完全二叉树的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h 层,则该层包含 1~ 2h 个节点。
h
Input: 1 / \ 2 3 / \ / 4 5 6 Output: 6
The text was updated successfully, but these errors were encountered:
/** * 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; } const leftDepth = countDepth(root.left); const rightDepth = countDepth(root.right); if (leftDepth === rightDepth) { return 1 + countNodes(root.right) + (1 << leftDepth) - 1; } else { return 1 + countNodes(root.left) + (1 << rightDepth) - 1; } }; function countDepth(patrol) { let depth = 0; while(patrol !== null) { depth++; patrol = patrol.left; } return depth; }
/** * Definition for a binary tree node. * class TreeNode { * val: number * left: TreeNode | null * right: TreeNode | null * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } * } */ function countNodes(root: TreeNode | null): number { if (root === null) { return 0; } const leftDepth = countDepth(root.left); const rightDepth = countDepth(root.right); if (leftDepth === rightDepth) { return 1 + countNodes(root.right) + (1 << leftDepth) - 1; } else { return 1 + countNodes(root.left) + (1 << rightDepth) - 1; } }; function countDepth(patrol: TreeNode | null): number { let depth = 0; while(patrol !== null) { depth++; patrol = patrol.left; } return depth; }
Sorry, something went wrong.
No branches or pull requests
222. Count Complete Tree Nodes
给出一个 完全二叉树,求出该树的节点个数。
Note
完全二叉树的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第
h
层,则该层包含 1~ 2h 个节点。Example
The text was updated successfully, but these errors were encountered: