Symmetric Tree 判断树是不是对称的

来源:互联网 发布:金融网络聊天技巧 编辑:程序博客网 时间:2024/05/21 14:51

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

判断树是不是对称,即判断它的左右子树是不是对称的。

我的方法是:

1. 镜像右子树。

2. 判断镜像右子树和左子树是不是相同的。

运行时间:



代码:

public class SymmetricTree {    public boolean isSymmetric(TreeNode root) {        if (root == null) {            return true;        }        return isSameTree(root.left, doMirror(root.right));    }    public TreeNode doMirror(TreeNode root) {        if (root == null) {            return root;        }        TreeNode temp = doMirror(root.left);        root.left = doMirror(root.right);        root.right = temp;        return root;    }    public boolean isSameTree(TreeNode p, TreeNode q) {        if (p == null && q == null) {            return true;        } else if (p == null || q == null) {            return false;        } else {            return p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);        }    }}


1 0
原创粉丝点击