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
1234512345 But the following is not:
1 / / 2 2 / / 3 3
1234512345 Note: Bonus points if you could solve it both recursively and iteratively.
一、中文
给定一棵树,判断它是否是对称的。即树的左子树是否是其右子树的镜像。
三、举例
上面的题目中给的就有例子,还是比较好理解的
四、思路
其实这个题目就是递归的使用,使用递归时候,首先要找到递归的终止条件,第二个就是递归的递推公式了,有了这两个就可以使用递归了
五、程序
package code;import java.util.Stack;class TreeNode{ int val; TreeNode left; TreeNode right; TreeNode(int x){ val = x; }}public class LeetCode50{ public static void main(String args[]){ TreeNode n1 = new TreeNode(1); TreeNode n2 = new TreeNode(2); TreeNode n3 = new TreeNode(3); TreeNode n4 = new TreeNode(4); TreeNode n5 = new TreeNode(5); n1.left = n2; n1.right = n3; n2.left = n4; n2.right = n5; TreeNode h1 = new TreeNode(1); TreeNode h2 = new TreeNode(2); TreeNode h3 = new TreeNode(3); TreeNode h4 = new TreeNode(4); TreeNode h5 = new TreeNode(5); h1.left = h2; h1.right = h3; //h2.left = h4; h2.right = h5; System.out.PRintln("比较的结果是:"+compareTwoTree(n1, h1)); } //第一种使用递归的方式 public static boolean compareTwoTree(TreeNode root1, TreeNode root2) { //递归的结束条件 if(root1 == null && root2 == null){ return true; } //也是递归的结束添加 if(root1 != null && root2 == null || root1 == null && root2 != null){ return false; } return root1.val == root2.val && compareTwoTree(root1.left, root2.left) && compareTwoTree(root1.right, root2.right); } } -------------------------------output-------------------------------比较的结果是:false