Leetcode 226 Invert Binary Tree
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.
题目大意:
翻转一棵二叉树。
测试样例见题目描述。
花絮:
这道题目的灵感来自于Max Howell的推特原文:
Google:我们90%的工程师在用你写的软件(Homebrew),但你竟然不会在白板上翻转一棵二叉树,所以滚吧。
解题思路:
递归或者队列迭代均可。
递归:
1、交换根节点的左右子树。
2、对左右子树分别执行递归反转 。
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 TreeNode* invertTree(TreeNode* root) { 13 //TreeNode* p = root; 14 if(root == NULL) 15 return root; 16 TreeNode* temp = root->left; 17 root->left = root->right; 18 root->right = temp; 19 invertTree(root->left); 20 invertTree(root->right); 21 return root; 22 } 23 };
1 TreeNode* invertTree(TreeNode* root) { 2 if(root==NULL) 3 return NULL; 4 TreeNode * ptmpNode = root->left; 5 root->left = invertTree(root->right); 6 root->right = invertTree(ptmpNode); 7 return root; 8 }
非递归算法:
1、交换根节点的左右子节点
2、交换第二层每个节点的左右子节点
....
这个与二叉树层次遍历类似,代码如下:
1 TreeNode* invertTree(TreeNode* root) { 2 if (root == NULL) 3 return root; 4 queue<TreeNode*> tree_queue; 5 tree_queue.push(root); 6 7 while (!tree_queue.empty()){ 8 TreeNode * pNode = tree_queue.front(); 9 tree_queue.pop(); 10 11 TreeNode * pLeft = pNode->left; 12 pNode->left = pNode->right; 13 pNode->right = pLeft; 14 15 if (pNode->left) 16 tree_queue.push(pNode->left); 17 if (pNode->right) 18 tree_queue.push(pNode->right); 19 } 20 return root; 21 }
越努力,越幸运