文章482
标签257
分类63

算法:对称的二叉树


对称的二叉树

对称的二叉树

请实现一个函数,用来判断一颗二叉树是不是对称的。

注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。


分析

类似于判断两个二叉树相等;

只不过是递归判断左子树和右子树相等;


代码

public class Solution {
    boolean isSymmetrical(TreeNode pRoot) {
        if (pRoot == null) return true;
        return helper(pRoot, pRoot);
    }

    private boolean helper(TreeNode root1, TreeNode root2) {
        if (root1 == null && root2 == null) return true;
        if (root1 == null || root2 == null) return false;
        if (root1.val != root2.val) return false;

        return helper(root1.left, root2.right) && helper(root1.right, root2.left);
    }
}

本文作者:Jasonkay
本文链接:https://jasonkayzk.github.io/1996/07/27/算法-对称的二叉树/
版权声明:本文采用 CC BY-NC-SA 3.0 CN 协议进行许可