Created
December 24, 2018 02:15
-
-
Save qiaoxu123/2f46c02f3b682fdf13abfad58e8d69ef to your computer and use it in GitHub Desktop.
思路自己能整理出来,但实现方式上存在一些问题。
一种是使用自己写的交换程序,另一种是使用std::swap,两者还是存在很多不同。 另外还有一种使用非递归进行实现
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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) { | |
// TreeNode* temp1; | |
// TreeNode* temp2; | |
// TreeNode* temp; | |
// if(root){ | |
// temp1 = invertTree(root->left); | |
// temp2 = invertTree(root->right); | |
// temp = temp1; | |
// temp1 = temp2; | |
// temp2= temp; | |
// } | |
// return root; | |
// } | |
//参考 | |
//打印正确 | |
TreeNode* invertTree(TreeNode* root) { | |
if (root) { | |
invertTree(root->left); | |
invertTree(root->right); | |
std::swap(root->left, root->right); | |
} | |
return root; | |
} | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//使用非递归实现 | |
TreeNode* invertTree(TreeNode* root) { | |
std::stack<TreeNode*> stk; | |
stk.push(root); | |
while (!stk.empty()) { | |
TreeNode* p = stk.top(); | |
stk.pop(); | |
if (p) { | |
stk.push(p->left); | |
stk.push(p->right); | |
std::swap(p->left, p->right); | |
} | |
} | |
return root; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment