1. 程式人生 > >判斷一棵二叉樹是否是對稱二叉樹

判斷一棵二叉樹是否是對稱二叉樹

class TreeNode {
     int val;
     TreeNode left;
     TreeNode right;
     TreeNode(int x) { val = x; }
 }
public class Solution {

    //判斷一棵樹是否為對稱二叉樹
    public boolean isSymmetric(TreeNode root) {
        if(root==null||(root.left==null&&root.right==null))
            return true;

        return
isSymmetricCheck(root,root); } //遞迴呼叫實現 public boolean isSymmetricCheck(TreeNode x,TreeNode y){ if(x==null&&y==null) return true; if((x!=null&&y==null)||(x==null&&y!=null)) return false; return (x.val==y.val)&&isSymmetricCheck(x.left,y.right)&&isSymmetricCheck(x.right,y.left); } public
static void main(String[]args){ //System.out.println("Hello Wolrd!"); TreeNode root=new TreeNode(1); root.left=new TreeNode(2); root.right=new TreeNode(2); root.left.left=new TreeNode(3); root.right.right=new TreeNode(3); Solution s=new Solution(); System.out
.println(s.isSymmetric(root)); } }