题目:
Invert a binary tree.
4
/
2 7
/ /
1 3 6 9
4
/
7 2
/ /
9 6 3 1
自己的(递归实现):
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* tem; 14 if (!root) 15 return 0; 16 tem = root->left; 17 root->left = root->right; 18 root->right = tem; 19 if(root->left) 20 invertTree(root->left); 21 if(root->right) 22 invertTree(root->right); 23 return root; 24 } 25 };
别人的:
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){ 14 swap(root->left, root->right); 15 invertTree(root->left); 16 invertTree(root->right); 17 } 18 return root; 19 } 20 };
自己的(使用队列,非递归实现):
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 queue<TreeNode*> queue; 14 if(!root) 15 return 0; 16 queue.push(root); 17 TreeNode *curNode; 18 while(!queue.empty()){ 19 curNode = queue.front(); 20 queue.pop(); 21 swap(curNode->left, curNode->right); 22 if(curNode->left) 23 queue.push(curNode->left); 24 if(curNode->right) 25 queue.push(curNode->right); 26 } 27 return root; 28 } 29 };
非递归和递归的在LeetCode上运行效率差不多。。。