首页 > 代码库 > Leetcode: Symmetric Tree

Leetcode: Symmetric Tree

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).For example, this binary tree is symmetric:    1   /   2   2 / \ / 3  4 4  3But the following is not:    1   /   2   2   \      3    3Note:Bonus points if you could solve it both recursively and iteratively.

难度:82. 这道题是树的题目,本质上还是树的遍历。这里无所谓哪种遍历方式,只需要对相应结点进行比较即可。一颗树对称其实就是看左右子树是否对称,一句话就是左同右,右同左,结点是对称的相等。不对称的条件有以下三个:(1)左边为空而右边不为空;(2)左边不为空而右边为空;(3)左边值不等于右边值。根据这几个条件在遍历时进行判断即可。

 1 /** 2  * Definition for binary tree 3  * public class TreeNode { 4  *     int val; 5  *     TreeNode left; 6  *     TreeNode right; 7  *     TreeNode(int x) { val = x; } 8  * } 9  */10 public class Solution {11     public boolean isSymmetric(TreeNode root) {12         if (root == null) return true;13         return check(root.left, root.right);14     }15     16     public boolean check(TreeNode node1, TreeNode node2) {17         if (node1 == null && node2 == null) return true;18         else if (node1 == null && node2 != null) return false;19         else if (node1 != null && node2 == null) return false;20         else if (node1.val != node2.val) return false;21         return check(node1.left, node2.right) && check(node1.right, node2.left);22     }23 }

Iterative的方式参考了网上的解法:

public boolean isSymmetric(TreeNode root) {    if(root == null)        return true;    if(root.left == null && root.right == null)        return true;    if(root.left == null || root.right == null)        return false;    LinkedList<TreeNode> q1 = new LinkedList<TreeNode>();    LinkedList<TreeNode> q2 = new LinkedList<TreeNode>();    q1.add(root.left);    q2.add(root.right);    while(!q1.isEmpty() && !q2.isEmpty())    {        TreeNode n1 = q1.poll();        TreeNode n2 = q2.poll();                if(n1.val != n2.val)            return false;        if(n1.left == null && n2.right != null || n1.left != null && n2.right == null)            return false;        if(n1.right == null && n2.left != null || n1.right != null && n2.left == null)            return false;        if(n1.left != null && n2.right != null)        {            q1.add(n1.left);            q2.add(n2.right);        }        if(n1.right != null && n2.left != null)        {            q1.add(n1.right);            q2.add(n2.left);        }                }    return true;}

 

Leetcode: Symmetric Tree