Symmetric Tree

来源:互联网 发布:xshell连接linux 编辑:程序博客网 时间:2024/06/06 12:27

题目:
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
做这道题,最好的解法我觉得应该是递归求解。开始我想的是先层序遍历,然后判断回文,发现不好使。后来收大神启发,用了递归,效率杠杠的。话不多说,上代码:

    public boolean isSymmetric(TreeNode root) {        return root == null || helpSmmetric(root.left, root.right);    }    public boolean helpSmmetric(TreeNode left, TreeNode right) {        //递归结束条件节点为空的情况,为空说明至少一个分支已经到低了,后面的也不需要在比较        if (left == null || right == null) {            return left == right;        }        //递归结束条件节点不为空的情况,只要不等直接返回false,后面不需要比较        if (left.val != right.val)            return false;        //递归调用可确保每次对比的节点都是对称的节点        return helpSmmetric(left.left, right.right) && helpSmmetric(left.right, right.left);    }

感觉递归好好用,我开始没用递归,写了好长的代码才勉强实现功能,然而递归核心步骤才几行。

原创粉丝点击