[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.

给一个二叉树判断是否为对称树。

解法1: 非递归,按层遍历,每一层检查一下是否对称。

解法2: 递归,

其中左子树和右子树对称的条件:1)两个节点值相等,或者都为空。2)左节点的左子树和右节点的右子树对称,左节点的右子树和右节点的左子树对称

Java:Recursion

class Solution {
    public boolean isSymmetric(TreeNode root) {
      if (root == null)
        return true;
      return isSymmetric(root.left, root.right);
    }

    public boolean isSymmetric(TreeNode l, TreeNode r) {
      if (l == null && r == null) {
        return true;
      } else if (r == null || l == null) {
        return false;
      }

      if (l.val != r.val)
        return false;

      if (!isSymmetric(l.left, r.right))
        return false;
      if (!isSymmetric(l.right, r.left))
        return false;

      return true;
    }
}

Java: Iteration

class Solution {
    public boolean isSymmetric(TreeNode root) {
        if(root == null)
            return true;
        if(root.left == null && root.right == null)
            return true;
        if(root.left == null || root.right == null)
            return false;
        LinkedList<TreeNode> q1 = new LinkedList<TreeNode>();
        LinkedList<TreeNode> q2 = new LinkedList<TreeNode>();
        q1.add(root.left);
        q2.add(root.right);
        while(!q1.isEmpty() && !q2.isEmpty()){
            TreeNode n1 = q1.poll();
            TreeNode n2 = q2.poll();

            if(n1.val != n2.val)
                return false;
            if((n1.left == null && n2.right != null) || (n1.left != null && n2.right == null))
                return false;
            if((n1.right == null && n2.left != null) || (n1.right != null && n2.left == null))
                return false;

            if(n1.left != null && n2.right != null){
                q1.add(n1.left);
                q2.add(n2.right);
            }

            if(n1.right != null && n2.left != null){
                q1.add(n1.right);
                q2.add(n2.left);
            }            
        }
        return true;
    }
}  

Python: Recursion

class Solution:
    # @param root, a tree node
    # @return a boolean
    def isSymmetric(self, root):
        if root is None:
            return True
        
        return self.isSymmetricRecu(root.left, root.right)
    
    def isSymmetricRecu(self, left, right):
        if left is None and right is None:
            return True
        if left is None or right is None or left.val != right.val:
            return False
        return self.isSymmetricRecu(left.left, right.right) and self.isSymmetricRecu(left.right, right.left)

Python: Iteration

class Solution:
    # @param root, a tree node
    # @return a boolean
    def isSymmetric(self, root):
        if root is None:
            return True
        stack = []
        stack.append(root.left)
        stack.append(root.right)
        
        while stack:
            p, q = stack.pop(), stack.pop()
            
            if p is None and q is None:
                continue
            
            if p is None or q is None or p.val != q.val:
                return False
            
            stack.append(p.left)
            stack.append(q.right)
            
            stack.append(p.right)
            stack.append(q.left)
            
        return True  

C++: Recursion

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isSymmetric(TreeNode *root) {
        if (!root) return true;
        return isSymmetric(root->left, root->right);
    }
    bool isSymmetric(TreeNode *left, TreeNode *right) {
        if (!left && !right) return true;
        if (left && !right || !left && right || left->val != right->val) return false;
        return isSymmetric(left->left, right->right) && isSymmetric(left->right, right->left);
    }
    
};

C++: Iteration

class Solution {
public:
    bool isSymmetric(TreeNode *root) {
        if (!root) return true;
        queue<TreeNode*> q1, q2;
        q1.push(root->left);
        q2.push(root->right);
        
        while (!q1.empty() && !q2.empty()) {
            TreeNode *node1 = q1.front();
            TreeNode *node2 = q2.front();
            q1.pop();
            q2.pop();
            if((node1 && !node2) || (!node1 && node2)) return false;
            if (node1) {
                if (node1->val != node2->val) return false;
                q1.push(node1->left);
                q1.push(node1->right);
                q2.push(node2->right);
                q2.push(node2->left);
            }
        }
        return true;
    }
};

   

All LeetCode Questions List 题目汇总

 

posted @ 2018-03-14 08:01  轻风舞动  阅读(617)  评论(0编辑  收藏  举报