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è)樹的鏡像,需要滿足如下條件:- 兩棵樹的根相等
- 左子樹是右子樹的鏡像
- 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);
}
}