LeetCode OJ 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 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.

判断一棵树是不是对称的,那么我们需要对比两个位置对称的节点,首先判断这两个节点的值是否相等,然后判断这两个节点的子树是否对称。这就是递归的思路,从根节点的左右子树开始,递归向下。代码如下:

 1 /**
 2  * Definition for a binary tree node.
 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 isSame(root.left, root.right);
14     }
15     
16     public boolean isSame(TreeNode root1, TreeNode root2){
17         if(root1==null && root2==null) return true;
18         if(root1!=null && root2!=null){
19             if(root1.val != root2.val) return false;
20             else{
21                 boolean a = isSame(root1.left, root2.right);
22                 boolean b = isSame(root1.right, root2.left);
23                 if(a==true && b==true) return true;
24                 else return false;
25             }
26         }
27         return false;
28     }
29 }

 

转载于:https://www.cnblogs.com/liujinhong/p/5453896.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值