首页 > 其他 > 详细

leetcode--101. Symmetric Tree

时间:2017-08-31 10:47:08      阅读:208      评论:0      收藏:0      [点我收藏+]

1、问题描述

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.

2、边界条件:root==null

3、思路:1)递归,对称结构是镜像;左手和右手的关系。所以应该左子树和右子树比较,右子树和左子树比较是否相同same。但是首先,从root开始分为左右子树。

base case:左右都为空--true,左右有一个为空--false

2)迭代:一层一层的比较,可以利用队列,前后取值比较是否相同。

4、代码实现

1)递归

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isSymmetric(TreeNode root) {
        if (root == null) {
            return true;
        }
        return isSameTree(root.left, root.right);
    }

    public boolean isSameTree(TreeNode p, TreeNode q) {
        if (p == null && q == null) {
            return true;
        }
        if (p == null || q == null) {
            return false;
        }

        return p.val == q.val
               && isSameTree(p.left, q.right)
               && isSameTree(p.right, q.left);
    }
}

2)迭代

5、api

 

leetcode--101. Symmetric Tree

原文:http://www.cnblogs.com/shihuvini/p/7456035.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!