我的LeetCode代码仓:https://github.com/617076674/LeetCode

原题链接:https://leetcode-cn.com/problems/count-complete-tree-nodes/description/

题目描述:

LeetCode222——完全二叉树的节点个数

知识点:层序遍历、递归

思路一:二叉树的层序遍历

时间复杂度和空间复杂度均是O(n),其中n为树中的节点个数。

JAVA代码:

public class Solution {
    public int countNodes(TreeNode root) {
        int result = 0;
        if(null == root){
            return result;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        TreeNode cur = root;
        queue.add(cur);
        while(!queue.isEmpty()){
            TreeNode treeNode = queue.poll();
            result++;
            if(null != treeNode.left){
                queue.add(treeNode.left);
            }
            if(null != treeNode.right){
                queue.add(treeNode.right);
            }
        }
        return result;
    }
}

LeetCode解题报告:

LeetCode222——完全二叉树的节点个数

思路二:利用满二叉树的性质递归求解

时间复杂度是O(h ^ 2),其中h为树的高度。空间复杂度是O(h)。

JAVA代码:

public class Solution {
    public int countNodes(TreeNode root) {
        if(root == null) {
            return 0;
        }
        int leftDepth = 0;
        TreeNode curLeft = root;
        while(curLeft.left != null) {
            curLeft = curLeft.left;
            leftDepth++;
        }
        int rightDepth = 0;
        TreeNode curRight = root;
        while(curRight.right != null) {
            curRight = curRight.right;
            rightDepth++;
        }
        if(rightDepth == leftDepth) {
            return (int)(Math.pow(2, leftDepth + 1) - 1);
        }
        return countNodes(root.left) + countNodes(root.right) + 1;
    }
}

LeetCode解题报告:

LeetCode222——完全二叉树的节点个数

 

相关文章: