Count Complete Tree Nodes

Given the root of a complete binary tree, return the number of the nodes in the tree.
Every level, except possibly the last, is completely filled in a complete binary tree, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h
Example 1:
Input: root = [1,2,3,4,5,6]
Output: 6

Approach

Java


public class CountCompleteTreeNodes {
    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        root.left.left = new TreeNode(4);
        root.left.right = new TreeNode(5);
        root.right.left = new TreeNode(6);

        System.out.println(countNodes(root));
    }

    // function to count tree nodes
    static int countNodes(TreeNode root) {

        // if tree is empty
        if (root == null)
            return 0;

        // if leaf node
        else if (root.left == null && root.right == null)
            return 1;

        // call for left subtree and right subtree
        return countNodes(root.left) + countNodes(root.right) + 1;
    }

}

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int valTreeNode leftTreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

C++

#include <bits/stdc++.h>
using namespace std;
//struct for treenode
struct TreeNode
{
    int data;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int data)
    {
        this->data = data;
        this->left = NULL;
        this->right = NULL;
    }
};

//function to count tree nodes
int countNodes(TreeNode *root)
{

    //if tree is empty
    if (root == NULL)
        return 0;

    //if leaf node
    else if (root->left == NULL && root->right == NULL)
        return 1;

    //call for left subtree and right subtree
    return countNodes(root->left) + countNodes(root->right) + 1;
}

int main()
{
    TreeNode *root = new TreeNode(1);
    root->left = new TreeNode(2);
    root->right = new TreeNode(3);
    root->left->left = new TreeNode(4);
    root->left->right = new TreeNode(5);
    root->right->left = new TreeNode(6);

    cout << countNodes(root);

    return 0;
}


No comments:

Post a Comment