Symmetric Tree 对称镜像树 @LeetCode

题目:

判断一个树是否为对称/镜像树


思路:

递归,先写出判断两个树是否为对称树:通过检查一个树的左子树是不是另一个树的右子树。。

再把一个树拆成两个子树来判断



/**
 * Symmetric Tree
 * 
 * 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.

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.


OJ's Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.

Here's an example:
   1
  / \
 2   3
    /
   4
    \
     5
The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".
 * */
public class S101 {

	public static void main(String[] args) {
		TreeNode n1 = new TreeNode(1);
		TreeNode n2 = new TreeNode(2);
		TreeNode n3 = new TreeNode(2);
		n1.left = n2;
		n1.right = n3;
		TreeNode n4 = new TreeNode(3);
		TreeNode n5 = new TreeNode(3);
		n2.right = n4;
		n3.left = n5;
		
		System.out.println(isSymmetric(n1));
	}

	public static boolean isSymmetric(TreeNode root) {
		// 不用继续比较了
		if(root == null){
			return true;
		}
		
		return isSymmetricRec(root.left, root.right);
    }
	
	// 比较一个树是不是对称树比较难写递归,所以改写成比较两个树是否对称树
	private static boolean isSymmetricRec(TreeNode t1, TreeNode t2){
		// 如果同时为空,则相等  
		if(t1==null && t2==null){
			return true;
		}else if(t1==null || t2==null){		// 如果一个空一个不空,则不等  
			return false;
		}
		
		// 根节点的值必须要相等!
		if(t1.val != t2.val){
			return false;
		}
		
		// 原来我这里还这样写,但是这有两个问题,
		// 一个是如果Java比较对象,即使里面是同样的值,如果非引用同一对象,则还是不一样!
		// 所以要区分是否为null的情况,比较麻烦!
		// 另一点是根本没必要做这个比较,因为递归会处理好!
		// 总结:只要写base case(没有节点或者只有一个节点)就够了,无需在base case里面
		// 处理更复杂的case,更复杂的在下面的return递归里写!
		/*
		if(t1.left != t2.right || t1.right!=t2.left){
			return false;
		}
		*/
		
		// 对称树的本质
		return isSymmetricRec(t1.left, t2.right) && isSymmetricRec(t1.right, t2.left);
	}
}



/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean isSymmetric(TreeNode root) {
        if(root == null){
            return true;
        }
        return isMirror(root.left, root.right);
    }
    
    public boolean isMirror(TreeNode r1, TreeNode r2){
        if(r1==null && r2==null){
            return true;
        }
        if(r1==null || r2==null){
            return false;
        }
        if(r1.val != r2.val){
            return false;
        }
        return isMirror(r1.left, r2.right) && isMirror(r1.right, r2.left);
    }
}


你可能感兴趣的:(Symmetric Tree 对称镜像树 @LeetCode)