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.
思路:也不知道怎么想出来的,原本觉得翻转二叉树应该用中序遍历(左中右),对应新树变为右中左即可,然而发现中序的话根节点无法正确建立,应该先建立根,再处理左右子树(前序).
于是算法思想为:前序递归遍历原树,然后新树(根为root2)的右子树用原树的左子树建立,新树的左子树用原树的右子树建立,如此递归.
TreeNode* invertTree(TreeNode* root) {
if (!root) return NULL;
TreeNode* root2 = new TreeNode(root->val);
root2->right = invertTree(root->left);
root2->left = invertTree(root->right);
return root2;
}
网友评论