输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
1 # -*- coding:utf-8 -*- 2 # class TreeNode: 3 # def __init__(self, x): 4 # self.val = x 5 # self.left = None 6 # self.right = None 7 class Solution: 8 def __init__(self): 9 self.maxlen = 0 10 11 def preOrder(self,root,length): 12 if root != None: 13 length += 1 14 self.preOrder(root.left,length) 15 self.preOrder(root.right,length) 16 if root.left == None and root.right == None: 17 self.maxlen = max(self.maxlen,length) 18 length -= 1 19 20 def TreeDepth(self, pRoot): 21 if pRoot == None: 22 return 0 23 self.preOrder(pRoot,0) 24 return self.maxlen 25 # write code here
Java版代码,leetcode地址:
1 class Solution { 2 int maxLen = 0; 3 4 public void preOrder(TreeNode root, int length) { 5 if (root != null) { 6 length++;// 遍历下一层节点,层数+1 7 preOrder(root.left, length); 8 preOrder(root.right, length); 9 if (root.left == null && root.right == null) { 10 // 叶子节点,计算一次最大深度 11 maxLen = Integer.max(maxLen, length); 12 } 13 length--;// 遍历完叶子节点,回退,层数-1 14 } 15 } 16 17 public int maxDepth(TreeNode root) { 18 if (root == null) { 19 return 0; 20 } 21 preOrder(root, 0); 22 return maxLen; 23 } 24 }
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
1 # -*- coding:utf-8 -*- 2 # class TreeNode: 3 # def __init__(self, x): 4 # self.val = x 5 # self.left = None 6 # self.right = None 7 class Solution: 8 def __init__(self): 9 self.isBalanced = True 10 11 def height(self,root): 12 if root == None or not self.isBalanced: 13 return 0 14 left = self.height(root.left) 15 right = self.height(root.right) 16 if abs(left - right) > 1: 17 self.isBalanced = False 18 return 1 + max(left,right) 19 20 def IsBalanced_Solution(self, pRoot): 21 self.height(pRoot) 22 return self.isBalanced 23 # write code here
Java版代码,leetcode地址:
1 class Solution { 2 boolean isBalanced = true; 3 4 public int height(TreeNode root) { 5 if (root == null || !isBalanced) { 6 return 0; 7 } 8 int left = height(root.left); 9 int right = height(root.right); 10 if (Math.abs(left - right) > 1) { 11 isBalanced = false; 12 } 13 return 1 + Integer.max(left, right); 14 } 15 16 public boolean isBalanced(TreeNode root) { 17 height(root); 18 return isBalanced; 19 } 20 }