判断一棵二叉树是否为对称树之java实现

package com.cb.java.algorithms.jianzhioffer.tree;

public class SymmetricTree {
	class TreeNode {
		int data; // 数据域
		TreeNode left;// 左子节点
		TreeNode right; // 右子节点

		public TreeNode(int data) {
			this.data = data;
		}
	}

	public boolean isSymmetric(TreeNode root) {
		// 树为空,则返回true
		if (root == null)
			return true;
		else
			return isSame(root.left, root.right);
	}

	private boolean isSame(TreeNode left, TreeNode right) {
		// 做右子节点都为空
		if (left == null && right == null)
			return true;
		else if (left == null || right == null)
			return false;
		// 左右子节点不为空则分别判断左右子树
		if (left != null && right != null) {
			return left.data == right.data && isSame(left.left, right.right) && isSame(left.right, right.left);
		}
		return false;
	}
}

你可能感兴趣的:(数据结构与算法)