已解答
简单
相关标签
相关企业
给你一个二叉树的根节点 root
,按 任意顺序 ,返回所有从根节点到叶子节点的路径。
叶子节点 是指没有子节点的节点。
示例 1:
输入:root = [1,2,3,null,5] 输出:["1->2->5","1->3"]
示例 2:
输入:root = [1] 输出:["1"]
222. 完全二叉树的节点个数
给你一棵 完全二叉树 的根节点 root
,求出该树的节点个数。
完全二叉树 的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h
层,则该层包含 1~ 2h
个节点。
示例 1:
输入:root = [1,2,3,4,5,6] 输出:6
示例 2:
输入:root = [] 输出:0
示例 3:
输入:root = [1] 输出:1
# 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
class Solution:
def countNodes(self, root: Optional[TreeNode]) -> int:
def countn(root):
if not root:
return 0
#需要把孩子的情况返回 所以用后序
#操作是直接操作 不用return/操作是要返回数值 如累加 则要return
left=countn(root.left) #左
right=countn(root.right) #右
totalnum=left+right+1 #中
return totalnum
return countn(root)
10. 平衡二叉树
给定一个二叉树,判断它是否是
平衡二叉树
示例 1:
输入:root = [3,9,20,null,null,15,7] 输出:true
示例 2:
输入:root = [1,2,2,3,3,null,null,4,4] 输出:false
示例 3:
输入:root = [] 输出:true
求高度用后序,求深度用前序
# 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
class Solution:
def isBalanced(self, root: Optional[TreeNode]) -> bool:
#通过递归求高度,通过判断高度差求是否平衡 用-1标志不平衡
if not root:
return True
def isb(root):
if not root: #递归结束标志,root为空,高度为0
return 0
left=isb(root.left) #左
right=isb(root.right) #右
if left==-1 or right==-1 or abs(left-right)>1: #判断高度差
return -1
return max(left,right)+1 #中
if isb(root)==-1:
return False
else:
return True
257. 二叉树的所有路径
给你一个二叉树的根节点 root
,按 任意顺序 ,返回所有从根节点到叶子节点的路径。
叶子节点 是指没有子节点的节点。
示例 1:
输入:root = [1,2,3,null,5] 输出:["1->2->5","1->3"]
示例 2:
输入:root = [1] 输出:["1"]
# 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
class Solution:
def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
if not root:
return []
result = []
def btp(root, exist):
if not root:
return
exist.append(str(root.val)) #中 节点,并是否是叶子结点从而输出
if not root.left and not root.right: # Leaf node
result.append("->".join(exist))
return
btp(root.left, exist.copy()) # Pass a copy of 'exist' to avoid modifying it #左
btp(root.right, exist.copy()) #右
btp(root, [])
return result
404. 左叶子之和
给定二叉树的根节点 root
,返回所有左叶子之和。
示例 1:
输入: root = [3,9,20,null,null,15,7] 输出: 24 解释: 在这个二叉树中,有两个左叶子,分别是 9 和 15,所以返回 24
示例 2:
输入: root = [1] 输出: 0
# 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
class Solution:
def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
def is_leaf(node):
return not node.left and not node.right
def sll(root):
if not root:
return 0
left=sll(root.left) #左
if root.left and is_leaf(root.left): #判断是否是叶子结点
left=root.left.val
right=sll(root.right) #右
sum=left+right #中
return sum
return sll(root)