当前位置:   article > 正文

蓝桥杯 第8天 树(2)_!leftnode

!leftnode

目录

1.226. 翻转二叉树 - 力扣(LeetCode) (leetcode-cn.com)

(1)递归写法

(2)迭代之深度优先

(3)迭代之广度优先

2.101. 对称二叉树 - 力扣(LeetCode) (leetcode-cn.com)

(1)递归

(2)迭代

3.100. 相同的树 - 力扣(LeetCode) (leetcode-cn.com)

(1)递归

(2)迭代法

4.572. 另一棵树的子树 - 力扣(LeetCode) (leetcode-cn.com)

5.104. 二叉树的最大深度 - 力扣(LeetCode) (leetcode-cn.com)

(1)后序遍历(通过高度求深度)

(2)先序遍历(回溯法)(直接求深度)

(3)层序遍历

6.559. N 叉树的最大深度 - 力扣(LeetCode) (leetcode-cn.com)

7.111. 二叉树的最小深度 - 力扣(LeetCode) (leetcode-cn.com)

8.222. 完全二叉树的节点个数 - 力扣(LeetCode) (leetcode-cn.com)

(1)前序遍历

(2)完全二叉树的性质

9.110. 平衡二叉树 - 力扣(LeetCode) (leetcode-cn.com)

10.257. 二叉树的所有路径 - 力扣(LeetCode) (leetcode-cn.com)

11.​​​​​​404. 左叶子之和 - 力扣(LeetCode) (leetcode-cn.com)

(1)后序遍历

(2)层序遍历

12.513. 找树左下角的值 - 力扣(LeetCode) (leetcode-cn.com)

13.112. 路径总和 - 力扣(LeetCode) (leetcode-cn.com)

(1)深度优先搜索

14.113. 路径总和 II - 力扣(LeetCode) (leetcode-cn.com)

15.106. 从中序与后序遍历序列构造二叉树 - 力扣(LeetCode) (leetcode-cn.com)

16.105. 从前序与中序遍历序列构造二叉树 - 力扣(LeetCode) (leetcode-cn.com)

17.654. 最大二叉树 - 力扣(LeetCode) (leetcode-cn.com)

18.617. 合并二叉树 - 力扣(LeetCode) (leetcode-cn.com)

(1)递归

(2)迭代写法


1.226. 翻转二叉树 - 力扣(LeetCode) (leetcode-cn.com)

(1)递归写法

  1. # Definition for a binary tree node.
  2. # class TreeNode:
  3. # def __init__(self, val=0, left=None, right=None):
  4. # self.val = val
  5. # self.left = left
  6. # self.right = right
  7. class Solution:
  8. def invertTree(self, root: TreeNode) -> TreeNode:
  9. if root==None:
  10. return None
  11. root.left,root.right=root.right,root.left
  12. self.invertTree(root.left)
  13. self.invertTree(root.right)
  14. return root

(2)迭代之深度优先

  1. # Definition for a binary tree node.
  2. # class TreeNode:
  3. # def __init__(self, val=0, left=None, right=None):
  4. # self.val = val
  5. # self.left = left
  6. # self.right = right
  7. class Solution:
  8. def invertTree(self, root: TreeNode) -> TreeNode:
  9. if root==None:
  10. return None
  11. stack=[root]
  12. while stack:
  13. top=stack.pop()
  14. top.left,top.right=top.right,top.left
  15. if top.left:
  16. stack.append(top.left)
  17. if top.right:
  18. stack.append(top.right)
  19. return root

(3)迭代之广度优先

  1. # Definition for a binary tree node.
  2. # class TreeNode:
  3. # def __init__(self, val=0, left=None, right=None):
  4. # self.val = val
  5. # self.left = left
  6. # self.right = right
  7. class Solution:
  8. def invertTree(self, root: TreeNode) -> TreeNode:
  9. if root==None:
  10. return None
  11. from collections import deque
  12. que=deque([root])
  13. while que:
  14. top=que.popleft()
  15. top.left,top.right=top.right,top.left
  16. if top.left:
  17. que.append(top.left)
  18. if top.right:
  19. que.append(top.right)
  20. return root

2.101. 对称二叉树 - 力扣(LeetCode) (leetcode-cn.com)

(1)递归

  1. # Definition for a binary tree node.
  2. # class TreeNode:
  3. # def __init__(self, val=0, left=None, right=None):
  4. # self.val = val
  5. # self.left = left
  6. # self.right = right
  7. class Solution:
  8. def isSymmetric(self, root: TreeNode) -> bool:
  9. return self.compare(root.left,root.right)
  10. def compare(self,left,right):
  11. if left==None and right==None:return True
  12. if left==None and right!=None:return False
  13. if left!=None and right==None:return False
  14. elif left.val!=right.val:return False
  15. x=self.compare(left.left,right.right)
  16. y=self.compare(left.right,right.left)
  17. return x and y

(2)迭代

  1. # Definition for a binary tree node.
  2. # class TreeNode:
  3. # def __init__(self, val=0, left=None, right=None):
  4. # self.val = val
  5. # self.left = left
  6. # self.right = right
  7. class Solution:
  8. def isSymmetric(self, root: TreeNode) -> bool:
  9. from collections import deque
  10. que=deque([])
  11. que.append(root.right)
  12. que.append(root.left)
  13. while que:
  14. leftnode=que.popleft()
  15. rightnode=que.popleft()
  16. if leftnode==None and rightnode==None:
  17. continue
  18. if not leftnode or not rightnode or leftnode.val != rightnode.val:
  19. return False
  20. que.append(leftnode.left)
  21. que.append(rightnode.right)
  22. que.append(leftnode.right)
  23. que.append(rightnode.left)
  24. return True

3.100. 相同的树 - 力扣(LeetCode) (leetcode-cn.com)

(1)递归

  1. # Definition for a binary tree node.
  2. # class TreeNode:
  3. # def __init__(self, val=0, left=None, right=None):
  4. # self.val = val
  5. # self.left = left
  6. # self.right = right
  7. class Solution:
  8. def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
  9. return self.compare(p,q)
  10. def compare(self,x,y):
  11. if x==None and y==None:
  12. return True
  13. if not x or not y or x.val!=y.val:
  14. return False
  15. a=self.compare(x.left,y.left)
  16. b=self.compare(x.right,y.right)
  17. return a and b

(2)迭代法

  1. # Definition for a binary tree node.
  2. # class TreeNode:
  3. # def __init__(self, val=0, left=None, right=None):
  4. # self.val = val
  5. # self.left = left
  6. # self.right = right
  7. class Solution:
  8. def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
  9. from collections import deque
  10. que=deque([])
  11. que.append(q)
  12. que.append(p)
  13. while que:
  14. x=que.popleft()
  15. y=que.popleft()
  16. if x==None and y==None:
  17. continue
  18. if not x or not y or x.val!=y.val:
  19. return False
  20. que.append(x.left)
  21. que.append(y.left)
  22. que.append(x.right)
  23. que.append(y.right)
  24. return True

4.572. 另一棵树的子树 - 力扣(LeetCode) (leetcode-cn.com)

有三种情况,一种是自己,一种是左孩子,一种是右孩子

一定要抽象起来

  1. # Definition for a binary tree node.
  2. # class TreeNode:
  3. # def __init__(self, val=0, left=None, right=None):
  4. # self.val = val
  5. # self.left = left
  6. # self.right = right
  7. class Solution:
  8. def isSubtree(self, root: TreeNode, subRoot: TreeNode) -> bool:
  9. if root==None:
  10. return False
  11. result1=self.compare(root,subRoot)
  12. result2=self.isSubtree(root.left,subRoot)
  13. result3=self.isSubtree(root.right,subRoot)
  14. return result1 or result2 or result3
  15. def compare(self,x,y):
  16. if x==None and y==None:
  17. return True
  18. if not x or not y or x.val!=y.val:
  19. return False
  20. a=self.compare(x.left,y.left)
  21. b=self.compare(x.right,y.right)
  22. return a and b

5.104. 二叉树的最大深度 - 力扣(LeetCode) (leetcode-cn.com)

(1)后序遍历(通过高度求深度)

  1. # Definition for a binary tree node.
  2. # class TreeNode:
  3. # def __init__(self, val=0, left=None, right=None):
  4. # self.val = val
  5. # self.left = left
  6. # self.right = right
  7. class Solution:
  8. def maxDepth(self, root: Optional[TreeNode]) -> int:
  9. return self.getheight(root)
  10. def getheight(self,root):
  11. if root==None:
  12. return 0
  13. lefth=self.getheight(root.left)
  14. righth=self.getheight(root.right)
  15. return max(lefth,righth)+1

(2)先序遍历(回溯法)(直接求深度)

python这边全局变量有点搞,最后只能通过一半的样例

  1. # Definition for a binary tree node.
  2. # class TreeNode:
  3. # def __init__(self, val=0, left=None, right=None):
  4. # self.val = val
  5. # self.left = left
  6. # self.right = right
  7. result=0
  8. class Solution:
  9. def maxDepth(self, root: Optional[TreeNode]) -> int:
  10. if root==None:
  11. return result
  12. self.getheight(root,1)
  13. return result
  14. def getheight(self,root,height):
  15. global result
  16. result=max(result,height)
  17. if root.left==None and root.right==None:
  18. return
  19. if root.left:
  20. self.getheight(root.left,height+1)
  21. if root.right:
  22. self.getheight(root.right,height+1)
  23. return

(3)层序遍历

  1. # Definition for a binary tree node.
  2. # class TreeNode:
  3. # def __init__(self, val=0, left=None, right=None):
  4. # self.val = val
  5. # self.left = left
  6. # self.right = right
  7. result=0
  8. class Solution:
  9. def maxDepth(self, root: Optional[TreeNode]) -> int:
  10. if root==None:
  11. return 0
  12. from collections import deque
  13. que=deque([root])
  14. ans=0
  15. while que:
  16. ans+=1
  17. size=len(que)
  18. for i in range(size):
  19. top=que.popleft()
  20. if top.left:
  21. que.append(top.left)
  22. if top.right:
  23. que.append(top.right)
  24. return ans

6.559. N 叉树的最大深度 - 力扣(LeetCode) (leetcode-cn.com)

  1. """
  2. # Definition for a Node.
  3. class Node:
  4. def __init__(self, val=None, children=None):
  5. self.val = val
  6. self.children = children
  7. """
  8. class Solution:
  9. def maxDepth(self, root: 'Node') -> int:
  10. if root==None:
  11. return 0
  12. depth=0
  13. for i in root.children:
  14. depth=max(depth,self.maxDepth(i))
  15. depth+=1
  16. return depth

7.111. 二叉树的最小深度 - 力扣(LeetCode) (leetcode-cn.com)

注意理解题意,叶子节点

  1. # Definition for a binary tree node.
  2. # class TreeNode:
  3. # def __init__(self, val=0, left=None, right=None):
  4. # self.val = val
  5. # self.left = left
  6. # self.right = right
  7. class Solution:
  8. def minDepth(self, root: TreeNode) -> int:
  9. if root==None:
  10. return 0
  11. if root.left==None and root.right!=None:
  12. return self.minDepth(root.right)+1
  13. if root.left!=None and root.right==None:
  14. return self.minDepth(root.left)+1
  15. return 1+min(self.minDepth(root.left),self.minDepth(root.right))

8.222. 完全二叉树的节点个数 - 力扣(LeetCode) (leetcode-cn.com)

(1)前序遍历

  1. # Definition for a binary tree node.
  2. # class TreeNode:
  3. # def __init__(self, val=0, left=None, right=None):
  4. # self.val = val
  5. # self.left = left
  6. # self.right = right
  7. class Solution:
  8. def countNodes(self, root: TreeNode) -> int:
  9. return self.getnum(root)
  10. def getnum(self,root):
  11. if root==None:
  12. return 0
  13. return 1+self.getnum(root.left)+self.getnum(root.right)

(2)完全二叉树的性质

  1. # Definition for a binary tree node.
  2. # class TreeNode:
  3. # def __init__(self, val=0, left=None, right=None):
  4. # self.val = val
  5. # self.left = left
  6. # self.right = right
  7. class Solution:
  8. def countNodes(self, root: TreeNode) -> int:
  9. if root==None:
  10. return 0
  11. left=root.left
  12. right=root.right
  13. leftnum=0
  14. rightnum=0
  15. while(left):
  16. left=left.left
  17. leftnum+=1
  18. while(right):
  19. right=right.right
  20. rightnum+=1
  21. if leftnum==rightnum:
  22. return (2**(leftnum+1))-1
  23. return 1+self.countNodes(root.left)+self.countNodes(root.right)

9.110. 平衡二叉树 - 力扣(LeetCode) (leetcode-cn.com)

  1. # Definition for a binary tree node.
  2. # class TreeNode:
  3. # def __init__(self, val=0, left=None, right=None):
  4. # self.val = val
  5. # self.left = left
  6. # self.right = right
  7. class Solution:
  8. def isBalanced(self, root: TreeNode) -> bool:
  9. a=self.getheight(root)
  10. if a==-1:
  11. return False
  12. return True
  13. def getheight(self,root):
  14. if root==None:
  15. return 0
  16. leftn=self.getheight(root.left)
  17. rightn=self.getheight(root.right)
  18. if leftn==-1:
  19. return -1
  20. if rightn==-1:
  21. return -1
  22. if abs(leftn-rightn)>1:
  23. return -1
  24. else:
  25. return 1+max(leftn,rightn)

10.257. 二叉树的所有路径 - 力扣(LeetCode) (leetcode-cn.com)

注意回溯的细节

  1. # Definition for a binary tree node.
  2. # class TreeNode:
  3. # def __init__(self, val=0, left=None, right=None):
  4. # self.val = val
  5. # self.left = left
  6. # self.right = right
  7. class Solution:
  8. def binaryTreePaths(self, root: TreeNode) -> List[str]:
  9. result=[]
  10. path=[]
  11. if root==None:
  12. return result
  13. self.traversal(root,result,path)
  14. return result
  15. def traversal(self,cur,result,path):
  16. cur.val=str(cur.val)
  17. path.append(cur.val)
  18. if not cur.left and not cur.right:
  19. ans="->".join(path)
  20. result.append(ans)
  21. return
  22. if cur.left:
  23. self.traversal(cur.left,result,path)
  24. path.pop()
  25. if cur.right:
  26. self.traversal(cur.right,result,path)
  27. path.pop()

11.​​​​​​404. 左叶子之和 - 力扣(LeetCode) (leetcode-cn.com)

(1)后序遍历

通过父节点来判断左节点是否为叶节点

  1. # Definition for a binary tree node.
  2. # class TreeNode:
  3. # def __init__(self, val=0, left=None, right=None):
  4. # self.val = val
  5. # self.left = left
  6. # self.right = right
  7. class Solution:
  8. def sumOfLeftLeaves(self, root: TreeNode) -> int:
  9. if root==None:
  10. return 0
  11. leftsum=self.sumOfLeftLeaves(root.left)
  12. rightsum=self.sumOfLeftLeaves(root.right)
  13. midsum=0
  14. if root.left and not root.left.left and not root.left.right:
  15. midsum=root.left.val
  16. return midsum+leftsum+rightsum

(2)层序遍历

  1. # Definition for a binary tree node.
  2. # class TreeNode:
  3. # def __init__(self, val=0, left=None, right=None):
  4. # self.val = val
  5. # self.left = left
  6. # self.right = right
  7. class Solution:
  8. def sumOfLeftLeaves(self, root: TreeNode) -> int:
  9. if root==None:
  10. return 0
  11. stack=[]
  12. stack.append(root)
  13. ans=0
  14. while stack:
  15. top=stack.pop()
  16. if top.left and not top.left.left and not top.left.right:
  17. ans+=top.left.val
  18. if top.left:
  19. stack.append(top.left)
  20. if top.right:
  21. stack.append(top.right)
  22. return ans

12.513. 找树左下角的值 - 力扣(LeetCode) (leetcode-cn.com)

(1)前序遍历

  1. # Definition for a binary tree node.
  2. # class TreeNode:
  3. # def __init__(self, val=0, left=None, right=None):
  4. # self.val = val
  5. # self.left = left
  6. # self.right = right
  7. class Solution:
  8. def findBottomLeftValue(self, root: Optional[TreeNode]) -> int:
  9. maxlen=-1
  10. leftvalue=0
  11. def traversal(root,depth):
  12. nonlocal maxlen,leftvalue
  13. if root.left==None and root.right==None:
  14. if depth>maxlen:
  15. maxlen=depth
  16. leftvalue=root.val
  17. return
  18. if root.left:
  19. traversal(root.left,depth+1)
  20. if root.right:
  21. traversal(root.right,depth+1)
  22. return
  23. traversal(root,0)
  24. return leftvalue

13.112. 路径总和 - 力扣(LeetCode) (leetcode-cn.com)

(1)深度优先搜索

  1. # Definition for a binary tree node.
  2. # class TreeNode:
  3. # def __init__(self, val=0, left=None, right=None):
  4. # self.val = val
  5. # self.left = left
  6. # self.right = right
  7. class Solution:
  8. def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
  9. if root==None:
  10. return False
  11. def dfs(root,sums):
  12. sums+=root.val
  13. if root.left==None and root.right==None:
  14. if sums==targetSum:
  15. return True
  16. return False
  17. if root.left:
  18. if dfs(root.left,sums):return True
  19. if root.right:
  20. if dfs(root.right,sums):return True
  21. return False
  22. return dfs(root,0)

14.113. 路径总和 II - 力扣(LeetCode) (leetcode-cn.com)

深度优先搜索

  1. # Definition for a binary tree node.
  2. # class TreeNode:
  3. # def __init__(self, val=0, left=None, right=None):
  4. # self.val = val
  5. # self.left = left
  6. # self.right = right
  7. class Solution:
  8. def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
  9. result=[]
  10. if root==None:
  11. return result
  12. def dfs(root,sums,path):
  13. nonlocal result
  14. sums+=root.val
  15. if root.left==None and root.right==None:
  16. if sums==targetSum:
  17. result.append(path+[root.val])
  18. return
  19. if root.left:
  20. dfs(root.left,sums,path+[root.val])
  21. if root.right:
  22. dfs(root.right,sums,path+[root.val])
  23. dfs(root,0,[])
  24. return result

15.106. 从中序与后序遍历序列构造二叉树 - 力扣(LeetCode) (leetcode-cn.com)

  1. # Definition for a binary tree node.
  2. # class TreeNode:
  3. # def __init__(self, val=0, left=None, right=None):
  4. # self.val = val
  5. # self.left = left
  6. # self.right = right
  7. class Solution:
  8. def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:
  9. if not postorder:
  10. return None
  11. rootnode=postorder[-1]
  12. root=TreeNode(rootnode)
  13. cut=inorder.index(rootnode)
  14. inlefttree=inorder[:cut]
  15. inrighttree=inorder[cut+1:]
  16. postlefttree=postorder[:len(inlefttree)]
  17. postrighttree=postorder[len(inlefttree):-1]
  18. root.left=self.buildTree(inlefttree,postlefttree)
  19. root.right=self.buildTree(inrighttree,postrighttree)
  20. return root

16.105. 从前序与中序遍历序列构造二叉树 - 力扣(LeetCode) (leetcode-cn.com)

  1. # Definition for a binary tree node.
  2. # class TreeNode:
  3. # def __init__(self, val=0, left=None, right=None):
  4. # self.val = val
  5. # self.left = left
  6. # self.right = right
  7. class Solution:
  8. def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
  9. if not preorder:
  10. return None
  11. rootnode=preorder[0]
  12. cut=inorder.index(rootnode)
  13. leftinorder=inorder[:cut]
  14. rightinorder=inorder[cut+1:]
  15. leftpreorder=preorder[1:1+len(leftinorder)]
  16. rightpreorder=preorder[1+len(leftinorder):]
  17. root=TreeNode(rootnode)
  18. root.left=self.buildTree(leftpreorder,leftinorder)
  19. root.right=self.buildTree(rightpreorder,rightinorder)
  20. return root

17.654. 最大二叉树 - 力扣(LeetCode) (leetcode-cn.com)

  1. # Definition for a binary tree node.
  2. # class TreeNode:
  3. # def __init__(self, val=0, left=None, right=None):
  4. # self.val = val
  5. # self.left = left
  6. # self.right = right
  7. class Solution:
  8. def constructMaximumBinaryTree(self, nums: List[int]) -> TreeNode:
  9. if not nums:
  10. return None
  11. rootvalue=max(nums)
  12. index=nums.index(rootvalue)
  13. root=TreeNode(rootvalue)
  14. root.left=self.constructMaximumBinaryTree(nums[:index])
  15. root.right=self.constructMaximumBinaryTree(nums[index+1:])
  16. return root

18.617. 合并二叉树 - 力扣(LeetCode) (leetcode-cn.com)

(1)递归

  1. # Definition for a binary tree node.
  2. # class TreeNode:
  3. # def __init__(self, val=0, left=None, right=None):
  4. # self.val = val
  5. # self.left = left
  6. # self.right = right
  7. class Solution:
  8. def mergeTrees(self, root1: TreeNode, root2: TreeNode) -> TreeNode:
  9. if not root1:
  10. return root2
  11. if not root2:
  12. return root1
  13. root1.val+=root2.val
  14. root1.left=self.mergeTrees(root1.left,root2.left)
  15. root1.right=self.mergeTrees(root1.right,root2.right)
  16. return root1

(2)迭代写法

  1. # Definition for a binary tree node.
  2. # class TreeNode:
  3. # def __init__(self, val=0, left=None, right=None):
  4. # self.val = val
  5. # self.left = left
  6. # self.right = right
  7. class Solution:
  8. def mergeTrees(self, root1: TreeNode, root2: TreeNode) -> TreeNode:
  9. if not root1:
  10. return root2
  11. if not root2:
  12. return root1
  13. from collections import deque
  14. que=deque([])
  15. que.append(root1)
  16. que.append(root2)
  17. while que:
  18. node1=que.popleft()
  19. node2=que.popleft()
  20. if node1.left and node2.left:
  21. que.append(node1.left)
  22. que.append(node2.left)
  23. if node1.right and node2.right:
  24. que.append(node1.right)
  25. que.append(node2.right)
  26. node1.val+=node2.val
  27. if not node1.left and node2.left:
  28. node1.left=node2.left
  29. if not node1.right and node2.right:
  30. node1.right=node2.right
  31. return root1
  1. # Definition for a binary tree node.
  2. # class TreeNode:
  3. # def __init__(self, val=0, left=None, right=None):
  4. # self.val = val
  5. # self.left = left
  6. # self.right = right
  7. class Solution:
  8. def mergeTrees(self, root1: TreeNode, root2: TreeNode) -> TreeNode:
  9. if not root1:
  10. return root2
  11. if not root2:
  12. return root1
  13. from collections import deque
  14. que=[]
  15. que.append(root2)
  16. que.append(root1)
  17. while que:
  18. node1=que.pop()
  19. node2=que.pop()
  20. if node1.left and node2.left:
  21. que.append(node2.left)
  22. que.append(node1.left)
  23. if node1.right and node2.right:
  24. que.append(node2.right)
  25. que.append(node1.right)
  26. node1.val+=node2.val
  27. if not node1.left and node2.left:
  28. node1.left=node2.left
  29. if not node1.right and node2.right:
  30. node1.right=node2.right
  31. return root1

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/451902
推荐阅读
相关标签
  

闽ICP备14008679号