检测对称二叉树

定一个二叉树,检查它是否是镜像对称的。

例如,二叉树 [1,2,2,3,4,4,3] 是对称的。

    1
   / \
  2   2
 / \ / \
3  4 4  3

但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:

    1
   / \
  2   2
   \   \
   3    3

说明:

如果你可以运用递归和迭代两种方法解决这个问题,会很加分。


递归方式:

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

迭代方式:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isSymmetric(TreeNode root) {
		
		if (root == null) {
			return true;
		}
		LinkedList<TreeNode> tLCur = new LinkedList<TreeNode>();
		LinkedList<TreeNode> tLNex = new LinkedList<TreeNode>();
		LinkedList<TreeNode> tRCur = new LinkedList<TreeNode>();
		LinkedList<TreeNode> tRNex = new LinkedList<TreeNode>();

		tLNex.add(root.left);
		tRNex.add(root.right);

		while (true) {
			if (tLNex.size() != tRNex.size()) {
				return false;
			}
			if (tLNex.size() == 0) {
				return true;
			}
			tLCur = tLNex;
			tLNex = new LinkedList<TreeNode>();
			tRCur = tRNex;
			tRNex = new LinkedList<TreeNode>();

			do {
				TreeNode tl = tLCur.removeFirst();
				TreeNode tr = tRCur.removeLast();
				if(tl==null && tr==null) {
					continue;
				}
				if(tl==null || tr==null) {
					return false;
				}
				if(tl.val!=tr.val) {
					return false;
				}
				tLNex.add(tl.left);
				tLNex.add(tl.right);
				tRNex.push(tr.right);
				tRNex.push(tr.left);
			} while (tLCur.size() > 0);
		}
    }
}


猜你喜欢

转载自blog.csdn.net/oro99/article/details/80951873