leetcode222. 完全二叉树的节点个数(java)

完全二叉树的节点个数

  • leetcode222. 完全二叉树的节点个数
    • 题目描述
  • 递归
  • 广度优先遍历
  • 二叉树专题

leetcode222. 完全二叉树的节点个数

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/count-complete-tree-nodes

题目描述

给你一棵 完全二叉树 的根节点 root ,求出该树的节点个数。
完全二叉树 的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h 层,则该层包含 1~ 2h 个节点。

示例1:
leetcode222. 完全二叉树的节点个数(java)_第1张图片
输入:root = [1,2,3,4,5,6]
输出:6

示例 2:
输入:root = []
输出:0

示例 3:
输入:root = [1]
输出:1

提示:
树中节点的数目范围是[0, 5 * 104]
0 <= Node.val <= 5 * 104
题目数据保证输入的树是 完全二叉树

递归

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */

 public int countNodes(TreeNode root) {
        if(root == null){
            return 0;
        }
        return process(root);
    }

	/**
	* 递归,递归左树 和 右树的信息,最后汇
	*/
    public int process(TreeNode root){
        if(root == null){
            return 0;
        }
        int left = process(root.left);
        int right = process(root.right);
        //左树节点数加右树节点数加头节点
        return left + right + 1;
    }

广度优先遍历

 public int countNodes(TreeNode root) {
        if(root == null){
            return 0;
        }
        return getNumNodes(root);
    }

/**
* 广度优先遍历
*/
 public int getNumNodes(TreeNode root){
 		//利用堆栈来实现
        Deque<TreeNode> nodeStack = new LinkedList<>();
        nodeStack.push(root);
       //初始化,头节点1个
        int num = 1;
        while(!nodeStack.isEmpty()){
            TreeNode cur = nodeStack.pop();
            if(cur != null){
              	//左树和右树分别计算
                if(cur.left != null){
                    nodeStack.push(cur.left);
                    num++;
                }
                if(cur.right != null){
                    nodeStack.push(cur.right);
                    num++;
                }
            }
        }
        return num;

    }

二叉树专题

leetcode199. 二叉树的右视图

leetcode109. 有序链表转换二叉搜索树

leetcode652. 寻找重复的子树

leetcode450. 删除二叉搜索树中的节点

leetcode701. 二叉搜索树中的插入操作

leetcode98. 验证二叉搜索树

leetcode700. 二叉搜索树中的搜索

你可能感兴趣的:(数据结构,java,算法,java,leetcode,算法,数据结构,动态规划)