剑指offer P157 二叉树镜像和对称二叉树

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/AK_97_CT/article/details/87031799

输入一个二叉树,将它变换为它的镜像。

方法一:递归

  /**
 * 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:
     //在遍历的时候交换左右儿子
    void MirrorInRecursion(TreeNode* root) {
        if(!root) return;
        if(!root->right&&!root->left) return;
        TreeNode* temp=root->left;
        root->left=root->right;
        root->right->temp;
        if(root->left) MirrorInRecursion(root->left);
        if(root->right) MirrorInRecursion(root->right);
    }
};

方法二: 非递归方法,采用迭代,借助栈

void MirrorInIteration(TreeNode* root) {
       if(!root) return;
        std::stack<TreeNode*> sta;
        sta.push(root);
        while(sta.size()>0)
        {
            TreeNode* root=sta.top();
            sta.pop();
            TreeNode* temp =root->left;
            root->left=root->right;
            root->right=temp;
            if(root->left) sta.push(root->left);
            if(root->right) sta.push(root->right);          
        }
    }

判断一棵树是否为对称二叉树(即,围绕它的中心对称)。

思路:两个节点n1, n2,我们需要比较n1的左子节点的值和n2的右子节点的值是否相等,同时还要比较n1的右子节点的值和n2的左子结点的值是否相等

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

猜你喜欢

转载自blog.csdn.net/AK_97_CT/article/details/87031799