Leetcode_101_Symmetric Tree

来源:互联网 发布:给游戏做美工需要什么 编辑:程序博客网 时间:2024/06/05 22:08

本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/42087039


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.


思路:

(1)题意为判断一棵树是否轴对称。

(2)该题和“判断两棵树是否完全相同”类似,是其强化版,思路大体是一样的。

(3)本文也是采用递归的思想。只要树根不为空,且有左右孩子,则将其左右孩子视为两棵树,本题进行的比较与“判断两棵树是否完全相同”是不一样的,本题比较的是树相反孩子节点的比较,即左孩子与右孩子、右孩子与左孩子的比较,而“判断两棵树是否完全相同”不仅如此,还有左孩子与左孩子、右孩子与右孩子的比较。

(4)希望本文对你有所帮助。


算法代码实现如下所示:

public boolean isSymmetric(TreeNode root) {    if(root==null){return true;}else if (root.left == null && root.right == null) {return true;} else if (root.left == null || root.right == null) {return false;} else {if (root.left.val != root.right.val) {return false;} else {return isSameTree(root.left, root.right);}}}public static boolean isSameTree(TreeNode r1, TreeNode r2) {if (r1 == null && r2 == null) {return true;} else if (r1 == null || r2 == null) {return false;} else {if (r1.val != r2.val) {return false;} else {boolean _left = isSameTree(r1.left, r2.right);boolean _right = isSameTree(r1.right, r2.left);if (_left && _right) {return true;} else {return false;}}}}


2 0