1. 程式人生 > >leetcode 104二叉樹的最大深度 & 111二叉樹最小深度

leetcode 104二叉樹的最大深度 & 111二叉樹最小深度

def maxDepth(root):
        """
        非遞迴,用棧表示,stack棧儲存節點
        """
        if not root:
            return 0
        count = 0
        stack = [root]  ####存放每一層的子節點
        tmp = []  ###臨時存放每一層的子節點,如果上一層都出棧,則stack = tmp
        while stack: 
            while stack:
                root = stack.pop(0)
                if root.left:
                    tmp.append(root.left)
                if root.right:
                    tmp.append(root.right)
            count += 1
            stack = tmp
            tmp = []
        return count 



def minDepth(self, root):
        """
        """
        if not root:
            return 0
        count = 0
        stack = [root]  ####存放每一層的子節點
        tmp = []
        while stack: 
            while stack:
                root = stack.pop(0)
                if root.left:
                    tmp.append(root.left)
                if root.right:
                    tmp.append(root.right)
                if not root.left and not root.right:
                    count += 1
                    return count
            count += 1
            stack = tmp
            tmp = []
        return count
def maxDepth(self, root):
        '''
        遞迴 
        '''
        if not root:
            return 0
        else:
            return max(self.maxDepth(root.left),self.maxDepth(root.right)) + 1


def minDepth(self, root):
        '''
        遞迴 
        '''
        if not root:
            return 0
        elif root.left and  root.right:
            return min(self.minDepth(root.left),self.minDepth(root.right)) + 1
        else:
            return max(self.minDepth(root.left),self.minDepth(root.right)) + 1