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
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 hExample 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 nodesstatic int countNodes(TreeNode root) {// if tree is emptyif (root == null)return 0;// if leaf nodeelse if (root.left == null && root.right == null)return 1;// call for left subtree and right subtreereturn countNodes(root.left) + countNodes(root.right) + 1;}}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;}}
C++
#include <bits/stdc++.h>using namespace std;//struct for treenodestruct TreeNode{int data;TreeNode *left;TreeNode *right;TreeNode(int data){this->data = data;this->left = NULL;this->right = NULL;}};//function to count tree nodesint countNodes(TreeNode *root){//if tree is emptyif (root == NULL)return 0;//if leaf nodeelse if (root->left == NULL && root->right == NULL)return 1;//call for left subtree and right subtreereturn 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