leetcode --226 Invert Binary Tree

实现考虑迭代的方法:

一直迭代交换左右子树:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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;
         
    }
};

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
   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;
}

  

 

posted @   hahahaf  阅读(127)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示