Count Complete Tree Nodes Solution LeetCode

Quoestion:Given a complete binary tree, count the number of nodes



Example1:
input:[1,2,3,4,5,6]
output:6
Example2:
input:[]
output:0

Algorithm:
Traverse through BST after visiting each node increase the count by 1 when we reach leaf node return count

You can follow any of the traversal algorithm.inorder is recomended

Python:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def __init__(self):
        self.c = 0
    def inorder(self,root):
        if not root:
            return self.c
        if root.left:
            self.inorder(root.left)
        self.c+=1
        # self.result.append(root.val)
        if root.right:
            self.inorder(root.right)
    def countNodes(self, root: TreeNode) -> int:
        self.inorder(root)
        return self.c
One Liner Python Code:
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def countNodes(self, root: TreeNode) -> int:
        if not root:
            return 0

        return 1+self.countNodes(root.left)+self.countNodes(root.right)
        

        


        

        

Post a Comment

0 Comments