222. 完全二叉树的节点个数 给出一个完全二叉树,求出该树的节点个数. 说明: 完全二叉树的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置.若最底层为第 h 层,则该层包含 1~ 2h 个节点. 示例: 输入: 1 / \ 2 3 / \ / 4 5 6 输出: 6 /** * Definition for a binary tree node. * public class TreeNode { * int…
完全二叉树的节点个数 给出一个完全二叉树,求出该树的节点个数. 说明: 完全二叉树的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置.若最底层为第 h 层,则该层包含 1~ 2h 个节点. 示例: 输入: 输出: 6 public class Solution { // 获取左子树的高度(其实是最左侧分支) public int getLeftHeight(TreeNode root) { int count =…
题目描述 给出一个完全二叉树,求出该树的节点个数. 说明: 完全二叉树的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置.若最底层为第 h 层,则该层包含 1~ 2h 个节点. 示例: 输入: 1 / \ 2 3 / \ / 4 5 6 输出: 6 解题思路 从根节点开始分别判断左右子树的高度: 若左子树高度等于右子树,说明左子树一定为满二叉树,可得左子树的总节点个数,然后递归求右子树的节点数: 若左子树高度大于右…
给出一个完全二叉树,求出该树的节点个数. 说明: 完全二叉树的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置.若最底层为第 h 层,则该层包含 1~ 2h 个节点. 示例: 输入: 1 / \ 2 3 / \ / 4 5 6 输出: 6 转别人解法: class Solution { public int countNodes(TreeNode root) { /** 完全二叉树的高度可以直接通过不断地访问左子树…
Leetcode之深度优先搜索(DFS)专题-559. N叉树的最大深度(Maximum Depth of N-ary Tree) 深度优先搜索的解题详细介绍,点击 给定一个 N 叉树,找到其最大深度. 最大深度是指从根节点到最远叶子节点的最长路径上的节点总数. 例如,给定一个 3叉树 : 我们应返回其最大深度,3. 说明: 树的深度不会超过 1000. 树的节点总不会超过 5000. N叉树的遍历,和二叉树的遍历一样. AC代码: /* // Definition for a Node. cl…
Leetcode:559. N叉树的最大深度 Leetcode:559. N叉树的最大深度 Talk is cheap . Show me the code . /* // Definition for a Node. class Node { public: int val; vector<Node*> children; Node() {} Node(int _val) { val = _val; } Node(int _val, vector<Node*> _children…
Given a complete binary tree, count the number of nodes. Definition of a complete binary tree from Wikipedia: In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as po…
Given a n-ary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. For example, given a 3-ary tree: We should return its max depth, which is 3. Note: The dept…
Given a complete binary tree, count the number of nodes. Note: Definition of a complete binary tree from Wikipedia:In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left…
题目 给出一个完全二叉树,求出该树的节点个数. 说明: 完全二叉树的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置.若最底层为第 h 层,则该层包含 1~ 2^h 个节点. 思路 1.如果一棵二叉树是完全二叉树,那么二叉树最大深度和右子树的最大深度是相同的话,那么根节点的左子树一定是一棵满二叉树,利用公式即可求出根节点的左子树的节点加上根节点的节点数量. 2.如果一棵二叉树是完全二叉树,那么二叉树最大深度和右子树…