Symmetric Tree

这里A这道题的时候,刚看到题目的时候想到用递归。后面题目也有提示,用递归或迭代。还是没有弄出来,主要参考了http://www.cnblogs.com/remlostime/archive/2012/11/15/2772230.html

LeetCode Oj:https://oj.leetcode.com/problems/

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  3

But the following is not:

    1
   / 
  2   2
      
   3    3

Note:
Bonus points if you could solve it both recursively and iteratively.

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.


OJ's Binary Tree Serialization:

The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.

Here's an example:

   1
  / 
 2   3
    /
   4
    
     5
The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".
 
 
 1 class TreeNode {
 2      int val;
 3      TreeNode left;
 4      TreeNode right;
 5      TreeNode(int x) { val = x; }
 6   }
 7 
 8 public class Solution {
 9     public boolean isSymmetric(TreeNode root) {        
10         if(null == root)
11             return true;
12         return check(root.left, root.right);
13     }
14     public boolean check(TreeNode leftNode, TreeNode rightNode){//开始有想到这样,用左右子节点
15         if(null == leftNode && null == rightNode) //两个都是空节点
16             return true;
17         if(null == leftNode || null == rightNode)//其中一个空节点
18             return false;
19         //两个都不是空节点
20         return leftNode.val == rightNode.val && check(leftNode.left, rightNode.right) 
21                 && check(leftNode.right, rightNode.left);//这里用的很漂亮,主要逻辑也在这里
22     }
23 }
原文地址:https://www.cnblogs.com/luckygxf/p/4049976.html