首页 > 学院 > 开发设计 > 正文

Leetcode037--判读二叉树是否对称

2019-11-06 06:43:43
字体:
来源:转载
供稿:网友

一、原题

  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  31234512345

  But the following is not:

    1   / /  2   2   /   /   3    31234512345

  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 
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表