标签:
Invert a binary tree.
4 / 2 7 / \ / 1 3 6 9to
4 / 7 2 / \ / 9 6 3 1Trivia:
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.
这道题可以采用队列,来进行广度优先搜索,对于二叉树,一行一行的进行遍历,每一次遍历时将左右子树进行倒换就可以了
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