leetcode之Symmetric Tree

来源:互联网 发布:范磊c语言 编辑:程序博客网 时间:2024/06/14 18:22

判断是不是对称树,用到递归思想就很方便。但是要注意递归结束的条件!

(1)C语言实现

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
 bool isMirror(struct TreeNode* p,struct TreeNode* q){
     if(p==NULL || q==NULL)
        return p==q;
    if(p->val!=q->val)
        return false;
    return isMirror(p->left,q->right)&&isMirror(p->right,q->left);
 }
bool isSymmetric(struct TreeNode* root) {
    if(root == NULL)
        return true;
    return isMirror(root->left,root->right);
}

(2)C++实现

/**
 * Definition for a binary tree node.
 * 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 == NULL)
            return true;
        return isMirror(root->left,root->right);
    }
    bool isMirror(TreeNode* p, TreeNode* q){
        if(p==NULL|| q==NULL)
            return p==q;
        if(p->val!=q->val)
            return false;
        return isMirror(p->left, q->right)&&isMirror(p->right, q->left);
    }
};

(3)java实现

/**
 * Definition for a binary tree node.
 * 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;
        return isMirror(root.left,root.right);
    }
    
    public boolean isMirror(TreeNode p, TreeNode q){
        if(p==null || q== null)
            return p==q;
        if(p.val!=q.val)
            return false;
        return isMirror(p.left,q.right)&&isMirror(p.right,q.left);
    }
}

0 0
原创粉丝点击