首页 > 代码库 > LeetCode 226 Invert Binary Tree
LeetCode 226 Invert Binary Tree
Problem:
Invert a binary tree.
4 / 2 7 / \ / 1 3 6 9
to
4 / 7 2 / \ / 9 6 3 1
Analysis:
1、helper function + recursion
一开始我用调用子函数,在子函数中递归的方式实现:
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 private: 12 void swapNode (TreeNode* root) { 13 TreeNode *tmp = root->left; 14 root->left = root->right; 15 root->right = tmp; 16 17 if (root->left != NULL) { 18 swapNode (root->left); 19 } 20 21 if (root->right != NULL) { 22 swapNode (root->right); 23 } 24 } 25 26 public: 27 TreeNode* invertTree(TreeNode* root) { 28 if (root != NULL) { 29 swapNode (root); 30 } 31 32 return root; 33 } 34 };
虽然解决了问题,但效率太低
2、recursion
进而将递归写入主函数中,并简化了部分代码
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 if (root == NULL) { 14 return root; 15 } 16 17 TreeNode *tmp = root->left; 18 root->left = invertTree(root->right); 19 root->right = invertTree(tmp); 20 21 return root; 22 } 23 };
效率有所提高
3、非递归方法
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 if (root == NULL) { 14 return NULL; 15 } 16 17 queue<TreeNode*> q; 18 q.push(root); 19 20 while (!q.empty()) { 21 TreeNode* cur = q.front(); 22 q.pop(); 23 24 TreeNode* tmp = cur->left; 25 cur->left = cur->right; 26 cur->right = tmp; 27 28 if (cur->left != NULL) { 29 q.push(cur->left); 30 } 31 32 if (cur->right != NULL) { 33 q.push(cur->right); 34 } 35 } 36 37 return root; 38 } 39 };
LeetCode 226 Invert Binary Tree
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。