【递归】【后续遍历】Leetcode 101 对称二叉树 100 相同的树
---------------🎈🎈对称二叉树 题目链接🎈🎈-------------------
101. 对称二叉树
解法一: 递归:后序遍历 左右中
时间复杂度O(N)
空间复杂度O(N)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isSymmetric(TreeNode root) {
// 递归
return compare(root.left, root.right);
}
public boolean compare(TreeNode left, TreeNode right){ // 确定递归的参数和返回值
if(left == null && right==null){return true;}
if(left != null && right==null){return false;}
if(left == null && right!=null){return false;}
if(left.val != right.val){return false;}
// 递归逻辑:继续比较左右两个子树的内外侧【相当于后序遍历,最后返回内侧和外侧的比较结果】
boolean compareOutside = compare(left.left, right.right);
boolean compareInside = compare(left.right, right.left);
return compareInside && compareOutside; // 内外侧都是true的时候就返回true
}
}
解法二: 迭代法,用了单端队列
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isSymmetric(TreeNode root) {
// 采用迭代法:用了单端队列
Queue<TreeNode> myqueue = new LinkedList<>();
myqueue.add(root.left);
myqueue.add(root.right);
while(!myqueue.isEmpty()){
TreeNode leftnode = myqueue.poll();
TreeNode rightnode = myqueue.poll();
if(leftnode == null && rightnode == null){
continue;
}
if(leftnode != null && rightnode == null){
return false;
}
if(leftnode == null && rightnode != null){
return false;
}
if(leftnode.val != rightnode.val){
return false;
}
myqueue.add(leftnode.left);
myqueue.add(rightnode.right);
myqueue.add(leftnode.right);
myqueue.add(rightnode.left);
}
return true;
}
}
100. 相同的树
解法一:深度优先
// 首先排除空节点的情况
// 排除了空节点,再排除数值不相同的情况
// 此时就是:左右节点都不为空,且数值相同的情况,此时才做递归,做下一层的判断
之后就是:判断左子树对应相同-判断右子树对应相同-合并结果返回根节点
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if(p == null && q==null) return true;
if(p == null && q != null) return false;
if(p != null && q == null) return false;
if(p.val != q.val) return false;
boolean leftresult = isSameTree(p.left, q.left);
boolean rightresult = isSameTree(p.right, q.right);
return leftresult && rightresult;
}
}