2016-03-08 49 views
-3
public static boolean isMirror(TreeNode left, TreeNode right){ 
     if (left==null && right==null){ 
      return true; 
     } 
     if (left!=null && right!=null) { 
      if (left.data == right.data) { 
       return (isMirror(left.left, left.right) && isMirror(right.left, right.right)); 
      } 

     } 
     return false; 

    } 

    public static boolean isSymmetric(TreeNode root){ 
     if (root==null){ 
      return true; 
     } 
     return isMirror(root.left, root.right); 
    } 


    public static void main(String[] args){ 
     TreeNode root=new TreeNode(); 
     TreeNode n1=new TreeNode(); 
     TreeNode n2=new TreeNode(); 
     TreeNode n3=new TreeNode(); 
     TreeNode n4=new TreeNode(); 

     root.left=n1; 
     root.right=n2; 
     n1.left=n3; 
     n2.right=n4; 


     root.data=3; 
     n1.data=6; 
     n2.data=6; 
     n3.data=1; 
     n4.data=1; 

我希望收到true,但我收到false。我想我已经错过了一两点。我应该如何解决它?我的树递归方法无法正常工作

+1

我认为它应该是'返回isMirror(left.left,right.left)&& isMirror(left.right,right.right);'。 – Tunaki

+3

开始使用调试器的好时机。 –

+3

为什么调试时你可以直接来到SO并且有人为你调试........? – redFIVE

回答

4

感谢Shire Resident建议:

public static boolean isMirror(TreeNode left, TreeNode right){ 
     if (left==null && right==null){ 
      return true; 
     } 
     if (left!=null && right!=null) { 
      if (left.data == right.data) { 
       //return (isMirror(left.left, left.right) && isMirror(right.left, right.right)); 
       return (isMirror(left.left, right.right) && isMirror(left.right, right.left)); 
      } 

     } 
     return false; 

    }