leetcode 226 Invert Binary Tree 翻转二叉树

Posted Joel_Wang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 };

 

以上是关于leetcode 226 Invert Binary Tree 翻转二叉树的主要内容,如果未能解决你的问题,请参考以下文章

leetcode 226 Invert Binary Tree

#Leetcode# 226. Invert Binary Tree

LeetCode 226. Invert Binary Tree

LeetCode226:Invert Binary Tree

Python解Leetcode: 226. Invert Binary Tree

Leetcode 226: Invert Binary Tree