1. 程式人生 > >LeetCode-101. Symmetric Tree(Java)

LeetCode-101. Symmetric Tree(Java)

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 class Solution {
    public boolean isSymmetric(TreeNode root) {
        if(root == null)
            return true;
        StringBuilder builderOfLeft = new StringBuilder();
		StringBuilder builderOfRight = new StringBuilder();
        String traverseLeft = traverseLeft(root,builderOfLeft);
        String traverseRight = traverseRight(root,builderOfRight);
        if(traverseLeft.equals(traverseRight)){
        	return true;
        }
        return false;
    }
    public static String traverseLeft(TreeNode root,StringBuilder builder){
    	if(root == null){
    		builder.append("null");
    		return null;
    	}
    	builder.append(root.val+"");
    	traverseLeft(root.left,builder);
    	traverseLeft(root.right,builder);
    	return builder.toString();
    }
    public static String traverseRight(TreeNode root,StringBuilder builder){
    	if(root == null){
    		builder.append("null");
    		return null;
    	}    		
    	builder.append(root.val+"");
    	traverseRight(root.right,builder);
    	traverseRight(root.left,builder); 
    	return builder.toString();
    }
}

這個耗時比較長,另外一種實現方式

public class Solution {
    public boolean isSymmetric(TreeNode root) {
        if (root == null) {
            return true;
        }
        return isSymmetric(root.left, root.right);
    }
    
    public boolean isSymmetric(TreeNode left, TreeNode right) {
        if (left == null && right == null) {
            return true;
        }
        
        if (left == null || right == null) {
            return false;
        }
        
        return left.val == right.val && isSymmetric(left.left, right.right) && isSymmetric(left.right, right.left);
    }
}