Symmetric Tree

题目链接

Symmetric Tree - LeetCode

注意点

  • 先判断结点是否为空再访问结点的值

解法

解法一:递归,从根结点开始判断,然后递归判断左子树的左子树和右子树的右子树以及左子树的右子树和右子树的左子树是否相等。

/**
 * 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 subTree(TreeNode* left,TreeNode* right)
    {
        if(!left && !right) return true;
        if((!left && right) || (left && !right) || (left->val != right->val)) return false;
        return subTree(left->left,right->right) && subTree(left->right,right->left);
    }
    bool isSymmetric(TreeNode* root) {
        if(!root) return true;
        return subTree(root->left,root->right);
    }
};

解法二:非递归,和递归思想一样,但是显式的用栈来模拟递归的过程。

/**
 * 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) return true;
        stack<TreeNode*> s;
        s.push(root->left);
        s.push(root->right);
        while(!s.empty())
        {
            TreeNode* p = s.top();
            s.pop();
            TreeNode* q = s.top();
            s.pop();
            if(!p && !q) continue;
            if((!p && q) || (p && !q) || (p->val != q->val)) return false;
            s.push(p->left);
            s.push(q->right);
            s.push(p->right);
            s.push(q->left);
        }
        return true;
    }
};

小结

  • 递归的本质就是利用栈实现的
原文地址:https://www.cnblogs.com/multhree/p/10505485.html