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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容