码疯窝

LeetCode 每日一题 — Symmetric Tree

2014/12/09 10:57:39    分类: 日志连载    0人评论 次浏览

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.

算法分析: 递归判断左节点是否与右节点对称, 时间复杂度: O(n), 空间复杂度 O(n)

Java:

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

C++:

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

Python:

# Definition for a  binary tree node
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    
    def isMirror(self, nl, nr):
        if nl == None and nr == None:
            return True
        if (nl == None and nr != None) or (nl != None and nr == None):
            return False
        return (nl.val == nr.val) and self.isMirror(nl.left, nr.right) and self.isMirror(nl.right, nr.left)
        
        
    # @param root, a tree node
    # @return a boolean
    def isSymmetric(self, root):
        if root == None:
            return True
        return self.isMirror(root.left, root.right)
继续查看有关 日志连载的文章

0个访客评论