226. 翻转二叉树
翻转一棵二叉树。
Solution1(递归版):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
class Solution { public: TreeNode* invertTree(TreeNode* root) { if(!root) return NULL; if(root->left) invertTree(root->left); if(root->right) invertTree(root->right); TreeNode* temp = root->left; root->left = root->right; root->right = temp; return root; } };
|
依次从叶子结点向上翻转。
Solution2(层次遍历版):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| class Solution { public: TreeNode* invertTree(TreeNode* root) { if(!root) return NULL; queue<TreeNode*> que; que.push(root); while(!que.empty()){ TreeNode* node = que.front(); que.pop(); TreeNode* nodeleft = node->left; node->left = node->right; node->right = nodeleft; if(node->left) que.push(node->left); if(node->right) que.push(node->right); } return root; } };
|
层次遍历,每到一个结点,就讲该结点下的子结点交换。