1. 程式人生 > >演算法題(三十六):對稱的二叉樹

演算法題(三十六):對稱的二叉樹

題目描述

請實現一個函式,用來判斷一顆二叉樹是不是對稱的。注意,如果一個二叉樹同此二叉樹的映象是同樣的,定義其為對稱的。

分析

從上而下遞迴掃描,只要發現左右結點不相同的返回false。

程式碼

public class Symmetry {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		TreeNode root = new TreeNode(1);
		root.left = new TreeNode(1);
		root.right = new TreeNode(1);
		root.left.left= new TreeNode(3);
		root.left.right = new TreeNode(3);
		root.right.left = new TreeNode(3);
		root.right.right = new TreeNode(3);
		System.out.println(symmetry(root));
	}
	
	public static boolean symmetry(TreeNode root){
		if(root == null){
			return true;
		}
		return comRoot(root.left, root.right);
		
	}
    private static boolean comRoot(TreeNode left, TreeNode right) {
        // TODO Auto-generated method stub
        if(left == null) return right==null;
        if(right == null) return false;
        if(left.value != right.value) return false;
        return comRoot(left.right, right.left) && comRoot(left.left, right.right);
    }

}