1. 程式人生 > >LeetCode 101. Symmetric Tree(對稱的樹)

LeetCode 101. 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.

方法一:遞迴,自頂向下

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

方法二:檢查中序遍歷的結果。
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    private TreeNode nullNode = new TreeNode(0);
    private List<TreeNode> traverse(TreeNode root) {
        List<TreeNode> inorder = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        TreeNode current = root;
        do {
            while (current != null) {
                stack.push(current);
                current = current.left;
            }
            if (!stack.isEmpty()) {
                current = stack.pop();
                inorder.add(current);
                current = current.right;
            }
        } while (current != null || !stack.isEmpty());
        return inorder;
    }
    public boolean isSymmetric(TreeNode root) {
        List<TreeNode> inorder = traverse(root);
        int l = 0, r = inorder.size()-1;
        while (l < r) {
            TreeNode left = inorder.get(l++);
            TreeNode right = inorder.get(r--);
            if (left.val != right.val) return false;
            if (left.left != null && right.right == null) return false;
            if (left.left == null && right.right != null) return false;
            if (left.right != null && right.left == null) return false;
            if (left.right == null && right.left != null) return false;
            if (left.left != null && right.right != null && left.left.val != right.right.val) return false;
            if (left.right != null && right.left != null && left.right.val != right.left.val) return false;
        }
        return true;
    }
}