码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode --226 Invert Binary Tree

时间:2017-08-02 00:43:10      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:ret   http   etc   cpp   bsp   alt   使用   保存   logs   

技术分享

实现考虑迭代的方法:

一直迭代交换左右子树:

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; 
    }

  

 

leetcode --226 Invert Binary Tree

标签:ret   http   etc   cpp   bsp   alt   使用   保存   logs   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!