LeetCode-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:

對(duì)稱二叉樹

But the following [1,2,2,null,3,null,3] is not:
非對(duì)稱二叉樹

Note:Bonus points if you could solve it both recursively and iteratively.
給定一個(gè)二叉樹,檢查是否是關(guān)于自己的鏡像。

算法分析

方法一(遞歸)
  • 分析
    一個(gè)樹如果是另一個(gè)樹的鏡像,需要滿足如下條件:
    1. 兩棵樹的根相等
    2. 左子樹是右子樹的鏡像
  • Java代碼
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean isSymmetric(TreeNode root) {
        return isMirror(root, root);//采用遞歸的思想
    }
    public boolean isMirror(TreeNode root1, TreeNode root2) {
        if (root1 == null && root2 == null) return true;
        if (root1 == null || root2 == null) return false;
        
        //節(jié)點(diǎn)相同,左子樹與右子樹為鏡像,然后遞歸
        return (root1.val == root2.val) && isMirror(root1.left, root2.right) && isMirror(root1.right, root2.left);
    }
}

參考

LeetCode

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容