Skip to content

Prepare For Coder Interview – Denny

  • Basic
  • Medium
  • Hard
  • Architect
  • Life

LeetCode: Count Complete Tree Nodes

Posted on January 10, 2018July 26, 2020 by braindenny

Count Complete Tree Nodes



Similar Problems:

  • CheatSheet: Leetcode For Code Interview
  • CheatSheet: Common Code Problems & Follow-ups
  • Tag: #recursive

Given a complete binary tree, count the number of nodes.

Definition of a complete binary tree from Wikipedia:
In a complete binary tree every level, except possibly the last, is completely filled, 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.

Github: code.dennyzhang.com

Credits To: leetcode.com

Leave me comments, if you have better ways to solve.


## https://code.dennyzhang.com/count-complete-tree-nodes
## Basic Ideas: Cut the examine dataset into half
##              Check height of sub-tree and right-tree
##              For each divide-conquer, one half will be solved without recursive
##
##    Sample Data: 
##             1        
##           /   \
##          2     3
##         /
##        4
##
## Complexity: Time O(h*log(n)) = O(log(n)*log(n)). Space O(1). If include system stack, Space O(log(n))
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def countNodes(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if root is None: return 0
        # root node is with height 0
        lh, rh = 0, 0
        lnode, rnode = root, root
        while lnode:
            lnode = lnode.left
            lh += 1
        while rnode:
            rnode = rnode.right
            rh += 1

        if lh == rh:
            return pow(2, lh) - 1
        else:
            return self.countNodes(root.left) + self.countNodes(root.right) + 1
linkedin
github
slack

Post Views: 9
Posted in HardTagged #binarytree, #classic, #inspiring, #recursive, redo

Post navigation

LeetCode: Combinations
LeetCode: Add Strings

Leave a Reply Cancel reply

Your email address will not be published.

Tags

#array #backtracking #bfs #binarytree #bitmanipulation #blog #classic #codetemplate #combination #dfs #dynamicprogramming #game #graph #greedy #heap #inspiring #interval #linkedlist #manydetails #math #palindrome #recursive #slidingwindow #stack #string #subarray #trie #twopointer #twosum binarysearch editdistance hashmap intervaldp knapsack monotone oodesign presum rectangle redo review rotatelist series sql treetraversal unionfind

Recent Posts

  • a
  • a
  • a
  • a
  • a

Recent Comments

    Archives

    Categories

    • Amusing
    • Basic
    • Easy
    • Hard
    • Life
    • Medium
    • Resource
    • Review
    • Series
    • Uncategorized
    Proudly powered by WordPress | Theme: petals by Aurorum.