226. 翻转二叉树
https://leetcode.cn/problems/invert-binary-tree/description/
public TreeNode invertTree(TreeNode root) {
invert(root);
return root;
}
public void invert(TreeNode node){
if (node == null) return;
TreeNode p = node.left;
node.left = node.right;
node.right = p;
invert(node.left);
invert(node.right);
}
101. 对称二叉树
https://leetcode.cn/problems/symmetric-tree/description/
public boolean isSymmetric(TreeNode root) {
return compare(root.left,root.right);
}
public boolean compare(TreeNode left,TreeNode right){
if (left == null && right != null) return false;
if (left != null && right == null) return false;
if (left == null && right == null) return true;
if (left.val != right.val) return false;
boolean out = compare(left.left, right.right);
boolean in = compare(left.right, right.left);
return out && in;
}
总结:本题只能用后序,因为要用到左右节点的信息,先知道左右节点分别底下的对不对称,再比这两个节点对不对称。 要不就用队列迭代也行。
标签:node,right,return,随想录,二叉树,TreeNode,null,第十五天,left From: https://www.cnblogs.com/jeasonGo/p/18084705