(剑指offer)55.二叉树的深度

输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。

class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None
class Solution:
    def TreeDepth(self, pRoot):
        # write code here
        """递归"""
        if pRoot==None:
            return 0
        else:
            return max(self.TreeDepth(pRoot.left),self.TreeDepth(pRoot.right))+1
    def TreeDepth2(self,pRoot):
        """非递归"""
        if not pRoot:
            return 0
        depth = 0
        stack,tag = [],[]
        pNode = pRoot
        while pNode or stack:
            while pNode:
                stack.append(pNode)
                tag.append(0)
                pNode=pNode.left
            if tag[-1]==1:
                depth = max(depth,len(stack))
                stack.pop()
                tag.pop()
                pNode=None # 这里要注意
            else:
                pNode = stack[-1]
                pNode = pNode.right
                tag.pop()
                tag.append(1)
        return depth

if __name__ == '__main__':
    Node1 = TreeNode(1)
    Node2 = TreeNode(2)
    Node3 = TreeNode(3)
    Node4 = TreeNode(4)
    Node5 = TreeNode(5)
    Node6 = TreeNode(6)
    Node7 = TreeNode(7)
    Node1.left = Node2
    Node1.right = Node3
    Node2.left = Node4
    Node2.right = Node5
    Node5.left = Node7
    Node3.right = Node6

    s = Solution()
    print(s.TreeDepth2(Node1))

你可能感兴趣的:(数据结构)