Likou 101: Symmetric Binary Tree

insert image description here
insert image description hereThe next step is to translate these problems into code form

class Solution {
    
    

public boolean isSymmetricChild(TreeNode leftTree,TreeNode rightTree){
    
      //定义左子树和右子树的一些情况方法
if(leftTree == null && rightTree == null){
    
      //都为空,是对称的
    return true;
}
if(leftTree == null && rightTree != null){
    
     //一个为空一个不为空
    return false;
}
if(leftTree != null && rightTree == null){
    
    
    return false;
}

if(leftTree.val != rightTree.val) return false;  //左子树对应的跟右子树不相等
return isSymmetricChild(leftTree.left,rightTree.right) && isSymmetricChild(leftTree.right,rightTree.left);
} //递归左子树左与右子树右 和左子树右和右子树左

    public boolean isSymmetric(TreeNode root) {
    
    
        if(root == null) return true; //空树,是
return (isSymmetricChild(root.left,root.right)); //左跟右的方法递归
    
}
    
}

It may still be confusing to look at the code, so let's expand the recursion and see the
insert image description herelink: Symmetric Binary Tree!

Guess you like

Origin blog.csdn.net/chenbaifan/article/details/123601726