leetcode题解-226-翻转二叉树 发表于 2019-12-16 | 更新于 2019-12-19 题目 My way 递归实现 12345678910111213141516171819202122/** * 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) return nullptr; TreeNode* tmp = invertTree(root->right); root->right = invertTree(root->left); root->left = tmp; return root; }}; 手动队列,层次遍历 1234567891011121314151617181920212223242526272829303132/** * 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) { queue<TreeNode*> q; q.push(root); while(!q.empty()) { auto front = q.front(); q.pop(); if (!front) continue; auto tmp = front->right; front->right = front->left; front->left = tmp; q.push(front->left); q.push(front->right); } return root; }};