LeetCode-101~Symmetric Tree

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3] is symmetric:

对称二叉树

But the following [1,2,2,null,3,null,3] is not:
非对称二叉树

Note:Bonus points if you could solve it both recursively and iteratively.
给定一个二叉树,检查是否是关于自己的镜像。

算法分析

方法一(递归)
  • 分析
    一个树如果是另一个树的镜像,需要满足如下条件:
    1. 两棵树的根相等
    2. 左子树是右子树的镜像
  • Java代码
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean isSymmetric(TreeNode root) {
        return isMirror(root, root);//采用递归的思想
    }
    public boolean isMirror(TreeNode root1, TreeNode root2) {
        if (root1 == null && root2 == null) return true;
        if (root1 == null || root2 == null) return false;
        
        //节点相同,左子树与右子树为镜像,然后递归
        return (root1.val == root2.val) && isMirror(root1.left, root2.right) && isMirror(root1.right, root2.left);
    }
}

参考

LeetCode

你可能感兴趣的:(LeetCode-101~Symmetric Tree)