226. Invert Binary Tree
Description:
Invert a binary tree.
Example:
Input:
4
/ \
2 7
/ \ / \
1 3 6 9
Output:
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 f*** off.
思路一:递归解法:交换根节点的左右子树,再分别对左右子树执行递归,终止条件为根节点没有左右子树时。
代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(root == NULL) return root;
TreeNode* tempRoot = root->left;
root->left = invertTree(root->right);
root->right = invertTree(tempRoot);
return root;
}
};
思路二:非递归解法,利用队列遍历树,从根节点开始依次交换每层节点的左右子节点。
代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(root == NULL) return root;
queue <TreeNode*> tree;
tree.push(root);
while(tree.size() > 0) {
TreeNode *currentRoot = tree.front();
tree.pop();
TreeNode *temp = currentRoot->left;
currentRoot->left = currentRoot->right;
currentRoot->right = temp;
if (currentRoot->left) {
tree.push(currentRoot->left);
}
if (currentRoot->right) {
tree.push(currentRoot->right);
}
}
return root;
}
};