226.翻转二叉树
题目:226. 翻转二叉树 - 力扣(LeetCode)
题解:代码随想录 (programmercarl.com)
思路较清晰
solution
public class Solution {
public TreeNode InvertTree(TreeNode root) {
if(root == null) return null;
root.left = InvertTree(root.left);
root.right = InvertTree(root.right);
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
return root;
}
}
summary
递归
层序
101.对称二叉树
题目:101. 对称二叉树 - 力扣(LeetCode)
题解:代码随想录 (programmercarl.com)
直接想到的办法是层序遍历+双端按队列判断每一层是否对称(写起来发现这个思路不太对?)
结果反而用递归思路做出来了
solution
public class Solution {
public bool IsSymmetric(TreeNode root) {
if (root == null) return false;
return symTraversal(root.left, root.right);
}
public bool symTraversal(TreeNode node1, TreeNode node2)
{
if (node1 == null && node2 == null) return true;
if (node1 == null || node2 == null) return false;
if (node1.val != node2.val) return false;
return (symTraversal(node1.left, node2.right) && symTraversal(node1.right, node2.left));
}
}
summary
key:
按左右相反的顺序遍历左子树和右子树并判断每个结点的值是否相等
思考的时候主要卡在怎么按相反顺序同时遍历两棵子树
错误:
判断相等的时候是判断值相等,而不是结点相等,结点肯定不相等;
判断值相等就要排除结点是null的情况,需要加一个条件判断
104.二叉树的最大深度
题目:104. 二叉树的最大深度 - 力扣(LeetCode)
题解:代码随想录 (programmercarl.com)
遍历到每个叶子节点更新深度
solution
public class Solution {
public int maxDepth;
public int MaxDepth(TreeNode root) {
int depth = 0;
depthTraversal(root, depth);
return maxDepth;
}
public void depthTraversal(TreeNode root, int depth)
{
if(root == null)
{
maxDepth = maxDepth > depth ? maxDepth : depth;
return;
}
depth ++;
depthTraversal(root.left, depth);
depthTraversal(root.right, depth);
}
}
summary
key:
方法参数depth和全局变量maxDepth
整数按值传递,每次递归拷贝了一个新的depth,最后在每个叶子节点处都可以得到一个该结点的depth,每次得到深度时更新全局变量即可。
上述说法有错误,上面的代码每次更新maxDepth并不是在叶子节点处
更新代码:
public class Solution {
public int maxDepth;
public int MaxDepth(TreeNode root) {
if (root == null) return 0;
int depth = 0;
depthTraversal(root, depth);
return maxDepth;
}
public void depthTraversal(TreeNode root, int depth)
{
depth ++;
if(root.left == null && root.right == null)
{
maxDepth = maxDepth >= depth ? maxDepth : depth;
return;
}
if(root.left != null) depthTraversal(root.left, depth);
if(root.right != null) depthTraversal(root.right, depth);
}
}
111.二叉树的最小深度
题目:111. 二叉树的最小深度 - 力扣(LeetCode)
题解:代码随想录 (programmercarl.com)
直觉是不能上题直接反过来判断最小吗,copy试一下,然后发现根结点只有右或左子树时不对,因为题目要求的是根节点到叶子结点的距离,然后发现自己上一题也是存在误区的
solution
public class Solution {
public int minDepth = int.MaxValue;
public int MinDepth(TreeNode root) {
if (root == null) return 0;
int depth = 0;
depthTraversal(root, depth);
return minDepth;
}
public void depthTraversal(TreeNode root, int depth)
{
depth ++;
if(root.left != null) depthTraversal(root.left, depth);
if(root.right != null) depthTraversal(root.right, depth);
if(root.left == null && root.right == null)
{
minDepth = minDepth <= depth ? minDepth : depth;
return;
}
}
}
summary
错误:
这一题和上面一题出现同一个误区,终止条件设为当前结点为null,这跟上一个结点是否为叶子结点没有任何关系。
叶子结点的判断的条件是左右结点都为空,这样上面两道题的代码就统一了