码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode_226题——Invert Binary Tree(队列,广度优先搜索)

时间:2015-07-22 20:35:16      阅读:103      评论:0      收藏:0      [点我收藏+]

标签:

Invert Binary Tree

 Total Accepted: 22352 Total Submissions: 62065My Submissions

Invert a binary tree.

     4
   /     2     7
 / \   / 1   3 6   9
to
     4
   /     7     2
 / \   / 9   6 3   1
Trivia:
This problem was inspired by this original tweet by Max Howell:
Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so fuck off.

 

Hide Tags
 Tree
Have you met this question in a real interview? 
Yes
 
No
 

Discuss

 

      这道题可以采用队列,来进行广度优先搜索,对于二叉树,一行一行的进行遍历,每一次遍历时将左右子树进行倒换就可以了

 1 #include<iostream>
 2 #include<queue>
 3 using namespace std;
 4 
 5   struct TreeNode {
 6       int val;
 7       TreeNode *left;
 8       TreeNode *right;
 9       TreeNode(int x) : val(x), left(NULL), right(NULL) {}
10   };
11 
12 TreeNode* invertTree(TreeNode* root) {
13     if(root==NULL||(root->left==NULL&&root->right==NULL))
14         return root;
15     queue<TreeNode*> qu;
16     qu.push(root);
17     while(!qu.empty())
18     {
19         TreeNode* temp=qu.front();
20         qu.pop();
21         if(temp->left!=NULL||temp->right!=NULL)
22         {
23             TreeNode* le=temp->left;
24             TreeNode* ri=temp->right;
25             temp->left=ri;
26             temp->right=le;
27         }
28         if(temp->left!=NULL)
29             qu.push(temp->left);
30         if(temp->right!=NULL)
31             qu.push(temp->right);
32     }
33     return root;
34 }
35 int main()
36 {
37 
38 }

 

leetcode_226题——Invert Binary Tree(队列,广度优先搜索)

标签:

原文地址:http://www.cnblogs.com/yanliang12138/p/4668260.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!