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

    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.

思路:

判断一棵树是否对称。bonus:使用递归和迭代两种方法实现
递归:判断根节点是否为空,空则是对称。否则判断左右子节点。
如果左右均为空,则对称。如果左空或右空,则不对称。
如果左子节点的值不等于右子节点,则不对称。
否则比较左子节点的左子节点和右子节点的右子节点,以及左子节点的右子节点和右子节点的左子节点。
依次递归
迭代:
用一个栈或者队列存储树种所有的值,模拟地规定的过程
/*public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}*/

 1 public class Solution101 {
 2     public boolean isSymmetric(TreeNode root) {
 3         if(root == null) return true;
 4         return isSymmetric(root.left,root.right);
 5     }
 6     public boolean isSymmetric(TreeNode left,TreeNode right){
 7         if(left == null && right == null) return true;
 8         if(left == null || right == null) return false;
 9         if(left.val != right.val) return false;
10         return isSymmetric(left.left, right.right) && isSymmetric(left.right,right.left);
11     }
12     public static void main(String[] args) {
13         // TODO Auto-generated method stub
14         Solution101 solution101 = new Solution101();
15         TreeNode root = new TreeNode(1);
16         root.left = new TreeNode(2);
17         root.right = new TreeNode(2);
18         root.left.left = new TreeNode(3);
19         root.left.right = new TreeNode(4);
20         root.right.left = new TreeNode(4);
21         root.right.right = new TreeNode(3);
22         if(solution101.isSymmetric(root) == true)
23             System.out.println("1");
24         else {
25             System.out.println("0");
26         }
27     }
28 
29 }
原文地址:https://www.cnblogs.com/zlz099/p/8184748.html