东寻

导航

对称的二叉树

题目描述

请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。

思路

递归判断左子树左节点的值是否等于右子树右节点的值,以及左子树右节点的值是否等于右子树左节点的值。

时间复杂度O(lgn),空间复杂度O(1)。

代码

/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    boolean check(TreeNode t1, TreeNode t2) {
        if(t1 == null && t2 == null)    return true;
        if(t1 == null || t2 == null)    return false;
        if(t1.val == t2.val) {
            return check(t1.left, t2.right) && check(t2.left, t1.right);
        }
        return false;
    }
    
    boolean isSymmetrical(TreeNode pRoot) {
        if(pRoot == null)    return true;
        return check(pRoot.left, pRoot.right);
    }
}

笔记

posted on 2020-03-20 13:15  东寻  阅读(196)  评论(0编辑  收藏  举报