leetcode 226 Invert Binary Tree 翻转二叉树

C++代码,方法层序+互换左右孩子

 

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     TreeNode* invertTree(TreeNode* root) {
13         //层序遍历然后互换每一层的左右孩子
14         if(root==NULL) return root;
15         queue<TreeNode*> q;
16         q.push(root);
17         while(!q.empty()){
18             TreeNode* cur=q.front();
19             TreeNode* temp;
20             q.pop();
21             if(cur->left!=NULL) q.push(cur->left);
22             if(cur->right!=NULL) q.push(cur->right);
23             if(cur->left!=NULL&&cur->right==NULL){
24                 cur->right=cur->left;cur->left=NULL;
25             }else if(cur->left==NULL&&cur->right!=NULL){
26                 cur->left=cur->right;cur->right=NULL;
27             }else if(cur->left!=NULL&&cur->right!=NULL){
28                 temp=cur->left;
29                 cur->left=cur->right;
30                 cur->right=temp;
31             }
32         }
33         return root;
34     }
35 };

 

posted @ 2019-02-27 00:15  Joel_Wang  阅读(136)  评论(0编辑  收藏  举报