Leetcode 101. Symmetric Tree 判断二叉树是否对称,注意写在两个方法中,递归时注意空的判断

来源:互联网 发布:linux 编译器gdb 编辑:程序博客网 时间:2024/06/06 08:46

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:

    1   / \  2   2 / \ / \3  4 4  3

But the following [1,2,2,null,3,null,3] is not:

    1   / \  2   2   \   \   3    3











/** * 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) {        if(root==null) return true;        return isSym(root.left,root.right);    }    public boolean isSym(TreeNode pleft,TreeNode pright){        if(pleft ==null && pright == null)return true;        //if(pleft ==null&&pright!=null || pright == null&&pleft!=null)return false;        //注意把pleft.val!=pright.val也写在这行会报空指针异常,因为还不确定pleft和pright是否有空的情况        if(pleft == null || pright == null) return false; //上面一行可以优化为这样。        if(pleft.val!=pright.val)return false;        return isSym(pleft.left,pright.right)&&isSym(pleft.right,pright.left);    }}



0 0
原创粉丝点击