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.
递归交换左右子树
[CODE]
-
-
-
-
-
-
-
-
-
- public class Solution {
- public TreeNode invertTree(TreeNode root) {
- if(root==null) return null;
-
- TreeNode temp = root.left;
- root.left = root.right;
- root.right = temp;
-
- invertTree(root.left);
- invertTree(root.right);
-
- return root;
- }
-
- }
非递归算法:
1、交换根节点的左右子节点
2、交换第二层每个节点的左右子节点
....
这个与二叉树层次遍历类似,代码如下:
- TreeNode* invertTree2(TreeNode* root) {
- queue<TreeNode*> tree_queue;
- if (root == NULL)
- return root;
- tree_queue.push(root);
- while(tree_queue.size() > 0){
- TreeNode * pNode = tree_queue.front();
- tree_queue.pop();
- TreeNode * pLeft = pNode->left;
- pNode->left = pNode->right;
- pNode->right = pLeft;
- if (pNode->left)
- tree_queue.push(pNode->left);
- if (pNode->right)
- tree_queue.push(pNode->right);
- }
- return root;
- }