zoukankan      html  css  js  c++  java
  • 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; 
        }
    

      

  • 相关阅读:
    1740-约数之和
    1653-南邮的面积
    1880-A. 偷吃可耻
    1429-全排列的输出
    1342-皇后控制问题
    1340-逆矩阵问题
    1319-n皇后问题
    1221-最少硬币问题
    1219-整数因子分解问题
    linux 命令小结
  • 原文地址:https://www.cnblogs.com/fanhaha/p/7271525.html
Copyright © 2011-2022 走看看