【Leetcode】222.完全二叉树的节点个数

 这题目一看就会有两种思路,一种是简单的DFS深度优先遍历,时间复杂度为O(n),每遍历到一个节点就增加sum incremented by 1,另一种方法就是从the last node开始算起,从下往上进行递归(这样才能够运用到完全二叉树的性质),但是我这里为了速度做出题目就直接使用DFS就可以求解了,代码如下:

# 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:
        self.geshu=0
        def DFS(root):
            if root==None:
                return 0
            else:
                DFS(root.left)
                if root!=None:
                    self.geshu+=1
                DFS(root.right)
        DFS(root)
        return self.geshu

 

posted @ 2021-04-08 13:21  Geeksongs  阅读(45)  评论(0编辑  收藏  举报

Coded by Geeksongs on Linux

All rights reserved, no one is allowed to pirate or use the document for other purposes.