nvert 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
雖然不知道Homebrew為何物,但是google 90%的人都用的產品絕對是高大上的,所以估且把這個trivia當成Max Howell在賣萌吧。
反轉二叉樹使用遞歸實現,可以看出,如果把左子樹和右子樹都反轉了的話,只需要交換它的左右子樹節點就可以了。而反轉子樹和反轉它自身是同一個問題,所以可以使用遞歸實現。
runtime:4ms
/**
* 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 NULL;
TreeNode * leftTree=NULL;
TreeNode * rightTree=NULL;
if(root->left)
leftTree=invertTree(root->left);
if(root->right)
rightTree=invertTree(root->right);
root->left=rightTree;
root->right=leftTree;
return root;
}
};
這道題還可以使用非遞歸來實現,非遞歸實現代碼可能會多了一點,但是也很好理解。使用一個隊列,開始時將根節點加入隊列中,然後交換它的左右子節點並將根節點從隊列中彈出,如果左右子節點非空,將左右子節點加入隊列中,一直處理到隊列中沒有元素為止。參考的解答:https://leetcode.com/discuss/40567/my-c-codes-recursive-and-nonrecursive
runtime:0ms
從運行時間可以看出研究一下非遞歸的解法還是很有意義的。
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
queue tbpNode;
if(root) tbpNode.push(root);
TreeNode *curNode, *temp;
while(!tbpNode.empty())
{
curNode = tbpNode.front();
tbpNode.pop();
temp = curNode->left;
curNode->left = curNode->right;
curNode->right = temp;
if(curNode->left) tbpNode.push(curNode->left);
if(curNode->right) tbpNode.push(curNode->right);
}
return root;
}
}