代码随想录算法训练营第十四天 | 226.翻转二叉树, 101. 对称二叉树,104.二叉树的最大深度 & 111.二叉树的最小深度
这期打卡我依旧是Python & C++交替
226. Invert Binary Tree
这题用前序和后序最方便!
题目链接:226. Invert Binary Tree
题目链接/文章讲解/视频讲解: 翻转二叉树
我的代码:
C++:
# 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 invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if not root:
return root
root.left, root.right = root.right, root.left
self.invertTree(root.left)
self.invertTree(root.right)
return root
101. Symmetric Tree
这一题理解对称的意义很关键,就是左右子树相互翻转后还是一样的就是对称,然后用后序。
题目链接:101. Symmetric Tree
题目链接/文章讲解/视频讲解: 对称二叉树
我的代码:
Python:
# 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 isSymmetric(self, root: Optional[TreeNode]) -> bool:
def dfs(left, right):
if left == None and right != None:
return False
elif left != None and right == None:
return False
elif left == None and right == None:
return True
elif left.val != right.val:
return False
else:
inside = dfs(left.right, right.left)
outside = dfs(left.left, right.right)
result = inside and outside
return result
if not root:
return True
return dfs(root.left, root.right)
104. Maximum Depth of Binary Tree
理解最大高度=最大深度是关键,然后使用后序
题目链接:104. Maximum Depth of Binary Tree
题目链接/文章讲解/视频讲解:二叉树的最大深度
我的代码:
C++:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int maxDepth(TreeNode* root) {
if (root == NULL) {
return 0;
}
int leftMax = maxDepth(root->left);
int rightMax = maxDepth(root->right);
return 1 + max(leftMax, rightMax);
}
};
111. Minimum Depth of Binary Tree
理解最小高度=最小深度是关键,然后使用后序
题目链接:111. Minimum Depth of Binary Tree
题目链接/文章讲解/视频讲解:二叉树的最小深度
我的代码:
Python:
# 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 minDepth(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
leftMin = self.minDepth(root.left)
rightMin = self.minDepth(root.right)
if not root.left and root.right:
return 1 + rightMin
elif not root.right and root.left:
return 1 + leftMin
else:
return 1 + min(leftMin, rightMin)
总结
继续加油!赶进度ing
二刷思路:用不同的语言刷;用不同的遍历方法刷