第一题:
- 二叉树节点的深度:指从根节点到该节点的最长简单路径边的条数。
- 二叉树节点的高度:指从该节点到叶子节点的最长简单路径边的条数。
求高度4321 一定要用后续遍历 LRD Post-Order Traversal
后序遍历是先求最小左右孩子节点,再返回高度+1,继续层层往上+1
求深度1234 一定要用前序遍历 VRD Pre-Order Traversal
# 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
# 递归法 DFS
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
if self.get_height(root) != -1:
return True
else:
return False
def get_height(self, root:TreeNode) -> int:
if not root:
return 0
#left child
left_height = self.get_height(root.left)
if left_height == -1:
return -1
#right child
right_height = self.get_right(root.right)
if right_height == -1:
return -1
#parent nood
#abs 是绝对值
if abs(left_height-right_height)>1:
return -1
else:
return 1+max(left_height,right_height)
# calculate the height of a binary tree. It returns the height of the current node in the tree,
# which is the maximum height between its left and right subtrees plus 1.
第二题:
没有理解。。。先背吧
Class Solution:
def traversal(self, cur, path, result):
path.append(cur.val)
if not cur.left and not cur.right:
sPath = '->'.join(map(str, path))
result.append(sPath)
return
if cur.left:
self.traversal(cur.left, path, result)
path.pop()
if cur.right:
self.traversal(cur.right, path, result)
path.pop()
def binaryTreePaths(self, root):
result = []
path = []
if not root:
return result
self.traversal(root, path, result)
return result
第三题:
跟其他题目不一样的地方:这次在parent node就需要判断是否有left child, and at the same time, the left child's left child and right child both are none.
use post order traversal: 只要把左子树的结果+右子树的结果加起来就是根节点之和
还是有点迷,先记代码吧
class Solution:
def sumOfLeftLeaves(self, root):
if root is None:
return 0
if root.left is None and root.right is None:
return 0
leftValue = self.sumOfLeftLeaves(root.left)
if root.left and not root.left.left and not root.left.right:
leftValue = root.left.val
rightValue = self.sumOfLeftLeaves(root.right)
sum_val = leftValue + rightValue
return sum_val