剑指offer 牛客网 二叉树的深度
# -*- coding: utf-8 -*- """ Created on Wed Apr 10 09:29:36 2019 @author: Administrator 题目: 输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点) 形成树的一条路径,最长路径的长度为树的深度。 思路:采用递归的思路,遍历到子节点,再返回,返回期间计数值加1,再递归 """ # -*- coding:utf-8 -*- 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 not pRoot: #如果空节点就返回0 return 0 #若为叶子节点就返回1 if pRoot and not pRoot.left and not pRoot.right: return 1 left = self.TreeDepth(pRoot.left) #开始遍历左子树 left += 1 #遍历后计数加1 right = self.TreeDepth(pRoot.right) #开始遍历右子树 right += 1 #遍历后计数加1 return max(left,right) #最终返回其最大的值 if __name__ == '__main__': solution = Solution() #1 2 3 4 5 6 7 8 node = TreeNode(8) node_left = TreeNode(1) node_right = TreeNode(3) node_left.left = node root_left = TreeNode(2) root_left.left = node_left root_left.right = node_right node_left = TreeNode(5) node_right = TreeNode(7) root_right = TreeNode(6) root = TreeNode(4) root.left = root_left root_right.left = node_left root_right.right = node_right root.right = root_right depth = solution.TreeDepth(root) print('depth: ',depth) #depth: 4