1. 程式人生 > >Leetcode 101. Symmetric Tree 驗證樹的對稱性 解題報告

Leetcode 101. Symmetric Tree 驗證樹的對稱性 解題報告

1 解題思想

這道題是上一道題的延伸版。
首先,題目的意思是說給了一顆樹,讓我們判斷他是否是對稱的(以根節點為中心,映象顛倒而成)

其實解題方式也很簡單,把根節點的左右節點開始,當做兩個獨立的子樹,判斷這兩個子樹的是否對稱

而判斷這兩個子樹是否對稱,就是在判斷兩個子樹的那個演算法那裡,把原來的左左對比,右右對比,改成左右對比和右左對比就可以了,稍稍改動一下位置就可以

2 原題

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 Note: Bonus points if you could solve it both recursively and iteratively.

3 AC解

/**
 * 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 check(TreeNode leftPart,TreeNode rightPart){ if(leftPart==null && rightPart==null) return true; if(leftPart==null || rightPart==null) return false; if(leftPart.val != rightPart.val) return
false; return check(leftPart.right,rightPart.left) && check(leftPart.left,rightPart.right); } public boolean isSymmetric(TreeNode root) { if(root == null) return true; return check(root.left,root.right); } }