力扣labuladong——一刷day42

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

文章目录

  • 前言
  • 一、力扣222. 完全二叉树的节点个数


前言


计算二叉树的节点个数,计算满二叉树的节点个数,计算完全二叉树的节点个数

一、力扣222. 完全二叉树的节点个数

/**
 * 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;
 *     }
 * }
 */
class Solution {
    public int countNodes(TreeNode root) {
        if(root == null){
            return 0;
        }
        return 1 + countNodes(root.left) + countNodes(root.right);
    }
}

更高效的解法

/**
 * 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;
 *     }
 * }
 */
class Solution {
    public int countNodes(TreeNode root) {
        if(root == null){
            return 0;
        }
        TreeNode l = root, r = root;
        int low = 0, high = 0;
        while(l != null){
            l = l.left;
            low ++;
        }
        while(r != null){
            r = r.right;
            high ++;
        }
        if(low == high){
            return (int)Math.pow(2, low) - 1;
        }
        return 1 + countNodes(root.left) + countNodes(root.right);
    }
}

你可能感兴趣的:(力扣题解,leetcode,算法,职场和发展,数据结构,java)