leetcode --226 Invert Binary Tree

实现考虑迭代的方法:

一直迭代交换左右子树:

class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
        if(root==NULL)
            return NULL;
      
        //if(root->left==NULL &&root->right==NULL)
        //    return root;
        TreeNode *temp=root->left;

        root->left=root->right;
        root->right=temp;
        if(root->left)
        cout<<root->left->val<<endl;
        if(root->right)
        cout<<root->right->val<<endl;
        
        
  
        invertTree(root->left);
        invertTree(root->right);
        return root;
        
    }
};

  不迭代的方法, 使用队列:

用队列保存要待要交换左右子树的兄弟节点

       if(root==NULL||(root->left==NULL&&root->right==NULL))
            return root;
        queue<TreeNode *> q;
        q.push(root);
        while(!q.empty())
        {
            
            TreeNode *temp=q.front();
            q.pop();
            if(temp!=NULL)
            {
            cout<<temp->val<<endl;
            TreeNode *t=temp->left;
            temp->left=temp->right;
            temp->right=t;
            q.push(temp->left);
            q.push(temp->right);
            }
        }
        
       return root; 
    }

  

原文地址:https://www.cnblogs.com/fanhaha/p/7271525.html