DFS traversal all nodes, and count at the same time
BFS traversal all nodes, and count at the same time
Strategy:
If height(root.left) = height(root.right), then n=2height+1
If height(root.left) > height(root.right), then n = 1+nums(root.left)+nums(root.left)
classSolution:defcountNodes(self,root: TreeNode) ->int:# DFS# edge caseif root ==None:return0 stack = [root] n =0whilelen(stack)!=0: root = stack.pop() n = n +1if root.left !=None: stack.append(root.left)if root.right !=None: stack.append(root.right)return n
Because traversal all nodes, time complexity = O(n) , space complexity = O(n)
classSolution:defcountNodes(self,root: TreeNode) ->int:# BFS# edge caseif root ==None:return0 queue = [root] n =0whilelen(queue)!=0: l =len(queue)for i inrange(l): root = queue.pop(0) n = n +1if root.left !=None: queue.append(root.left)if root.right !=None: queue.append(root.right)return n
Because traversal all nodes, time complexity = O(n) , space complexity = O(n)
Time complexity = O(n) , space complexity = O(1) . This is the worst case, generally it's not necessary to traversal all nodes.
Be careful with two points:
1+21+22+...+2n=2n+1−1
Height of left subtree is always to traversal left child, Height of right subtree is always to traversal right child. Because we want to find max height of left subtree and min height of right subtree.
classSolution:defcountNodes(self,root: TreeNode) ->int:# edge caseif root ==None:return0# regular case left = self.leftHeight(root.left) right = self.rightHeight(root.right)if left == right: n =pow(2, left+1)-1else: n =1+ self.countNodes(root.left)+ self.countNodes(root.right)return ndefleftHeight(self,root):# stop conditionif root ==None:return0return1+ self.leftHeight(root.left)defrightHeight(self,root):# stop conditionif root ==None:return0return1+ self.rightHeight(root.right)