[LeetCode] - Symmetric Tree

来源:互联网 发布:盗号软件万能钥匙 编辑:程序博客网 时间:2024/06/04 19:45

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.

1. 以下是常规的recursive解法,没啥可说的,挨着个儿检查就是了。

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

2. 以下是iterative的解法。其实也没啥好说的,就是用level order traversal的方式来检查,BFS算法。如果碰到null的情况,加一个特殊值到list里面就可以了。这个有点儿像binary tree的serialization时用到的思想。

/** * Definition for binary tree * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public boolean isSymmetric(TreeNode root) {        if(root==null) return true;                Queue<TreeNode> frontier = new LinkedList<TreeNode>();        frontier.add(root);        while(!frontier.isEmpty()) {            Queue<TreeNode> next = new LinkedList<TreeNode>();            Stack<Integer> stack1 = new Stack<Integer>();            Stack<Integer> stack2 = new Stack<Integer>();            boolean flag = false;                        while(!frontier.isEmpty()) {                TreeNode temp = frontier.poll();                if(temp != null) {                    stack1.push(temp.val);                    if(temp.left != null) {                        next.add(temp.left);                        if(!flag) flag=true;                    }                    else next.add(null);                    if(temp.right != null) {                        next.add(temp.right);                        if(!flag) flag=true;                    }                    else next.add(null);                }                else stack1.push(-100);            }            int size=stack1.size(), i=0;            while(i < size/2) {                stack2.push(stack1.pop());                i++;            }            if(size%2!=0 && !stack1.isEmpty()) stack1.pop();            while(!stack1.isEmpty()) {                if(stack1.pop()!=stack2.pop()) return false;            }                        if(!flag) frontier.clear();            else frontier=next;        }        return true;    }}

0 0