判斷二叉樹是否是鏡像對稱


給定一個二叉樹,檢查它是否是鏡像對稱的。

 例如,二叉樹 [1,2,2,3,4,4,3] 是對稱的。

     1
    / \
   2   2
  / \ / \
 3  4 4  3
  但是下面這個 [1,2,2,null,3,null,3] 則不是鏡像對稱的:

     1
    / \
   2   2
    \   \
   3    3

思路:用高度大於2的二叉樹舉例來說吧,也就是上面第一個例子,只要結點1的左孩子和結點2的右孩子相等,並且結點1的右孩子和結點2的左孩子相等,我們就認為是鏡像,前提是結點1和結點2兄弟結點;

遞歸實現如下:

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


    //遞歸
    public static boolean in(TreeNode l1,TreeNode l2){
        if(l1 == null && l2 == null) return true;
        if(l1 == null || l2 == null) return false;
        return l1.val == l2.val && in(l1.left,l2.right) && in(l1.right,l2.left);
    }

非遞歸如下:

//迭代
    public static boolean isSymm(TreeNode root){
        if(root == null) return true;
        Queue<TreeNode> q = new LinkedList<>();
        q.add(root);
        q.add(root);
        while (!q.isEmpty()) {
            TreeNode t1 = q.poll();
            TreeNode t2 = q.poll();
            if (t1 == null && t2 == null) continue;
            if (t1 == null || t2 == null) return false;
            if (t1.val != t2.val) return false;
            q.add(t1.left);
            q.add(t2.right);
            q.add(t1.right);
            q.add(t2.left);
        }
        return true;
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM