首页 > 其他 > 详细

leetcode --226 Invert Binary Tree

时间:2017-08-01 23:38:03      阅读:253      评论:0      收藏:0      [点我收藏+]

技术分享

实现考虑迭代的方法:

一直迭代交换左右子树:

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!