即日起在codingBlog上分享您的技术经验即可获得积分,积分可兑换现金哦。

个人记录-LeetCode 101. Symmetric Tree

编程语言 Gaugamela 15℃ 0评论

问题:


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

这个问题是要判断一棵树是否镜像对称。

代码示例:


最简单好理解的方法,就是利用递归了,例如:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */

public class Solution {
    public boolean isSymmetric(TreeNode root) {
        return (root == null) || (innerHelper(root.left, root.right));
    }

    private boolean innerHelper(TreeNode left, TreeNode right) {
        if (left == null || right == null) {
            return left == right;
        }

        //判断左右节点的值是否相等
        return (left.val == right.val)
                //然后根据镜像对称的关系,比较左节点的左子树和右节点的右子树
                && innerHelper(left.left, right.right)
                //以及左节点的右子树和右节点的左子树
                && innerHelper(left.right, right.left);
    }
}

转载请注明:CodingBlog » 个人记录-LeetCode 101. Symmetric Tree

喜欢 (0)or分享 (0)
发表我的评论
取消评论

*

表情