算法 101. Symmetric Tree

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; }
 * }
 */
class Solution {
    public boolean isSymmetric(TreeNode root) {
        
    }
}

給一個二叉樹,檢查下是不是自我鏡像的(圍繞中間對稱)。
解:
思路一:遞歸。遞歸去判斷,當前節(jié)點的左節(jié)點是否與右節(jié)點相同,不同返回 false。
思路二:遍歷或者叫迭代。和遞歸差不多,只不過不是使用遞歸的方式。
思路三:旋轉。這是我一剛開始的想法, 不停遞歸旋轉左右子樹,再去判斷與原樹是否相同,這復雜度還不如直接判斷。

以下為代碼:
遞歸方式:

public boolean isSymmetric(TreeNode root) {
    return isMirror(root, root);
}

public boolean isMirror(TreeNode t1, TreeNode t2) {
    if (t1 == null && t2 == null) {
        return true;
    }
    if (t1 == null || t2 == null) {
        return false;
    }
    return (t1.val == t2.val)
        && isMirror(t1.right, t2.left)
            && isMirror(t1.left, t2.right);
}

迭代方式:

public boolean isSymmetric(TreeNode root) {
    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;
}
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

  • 目錄 簡書的 markdown 都不支持 [TOC] 語法……我就不貼目錄了。下面按照類別,列出了29道關于二叉樹...
    被稱為L的男人閱讀 3,447評論 0 8
  • 總結類型: 完全子樹(#222) BST(左右子樹值的性質,注意不僅要滿足parent-child relatio...
    __小赤佬__閱讀 774評論 0 0
  • 1. Binary Tree Preorder Traversal Description Given a bin...
    BookThief閱讀 693評論 0 0
  • Validate Binary Search Tree Same Tree (基礎) 101.symmetric ...
    lifesmily閱讀 360評論 0 0
  • 說起小時候,真是一段快樂和幸福的日子。 我出生在安徽的一個小村子里,上小學之前,我的思維都活躍在那里,以為世界就那...
    isaky閱讀 330評論 9 5

友情鏈接更多精彩內容