Solved LeetCode problem 222: Count Complete Tree Nodes

Leetcode problem solving day 88 today i solved problem number 222. Count Complete Tree Nodes link to problem - https://lnkd.in/gWVKj_hb below is my approch Approach 1: Linear Time count nodes recursively one by one. class Solution {  public int countNodes(TreeNode root) {   return root != null ? 1 + countNodes(root.right) + countNodes(root.left) : 0;  } } Time complexity : O(N). Space complexity :O(logN) Approach 2: Binary search Return 0 if the tree is empty. Compute the tree depth d. Return 1 if d == 0. The number of nodes in all levels but the last one is 2 to the power d−1. The number of nodes in the last level could vary from 1 to 2 to the power d. Enumerate potential nodes from 0 to 2 to the power d−1. and perform the binary search by the node index to check how many nodes are in the last level. Use the function exists(idx, d, root) to check if the node with index idx exists. Use binary search to implement exists(idx, d, root) as well. Return 2 to the power d−1 + the number of nodes in the last level. Time complexity :O(log square N) Space complexity : O(1)     #DSA  #Programming  #LeetCode #ProblemSolving #CodingJourney #TechCommunity   

  • graphical user interface, text, application

To view or add a comment, sign in

Explore content categories