【easy】226. Invert Binary Tree 反转二叉树

时间:2022-08-04 07:40:21

【easy】226. Invert Binary Tree 反转二叉树

/**
* 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 == NULL) {
return NULL;
} TreeNode *tempNode = root->left;
root->left = root->right;
root->right = tempNode; invertTree(root->left);
invertTree(root->right); return root;
}
};

下面是非递归的一种写法:(可以说是很漂亮了)

TreeNode* invertTree(TreeNode* root)
{
if(root == NULL)return NULL;
vector<TreeNode*> stack;
stack.push_back(root);
while(!stack.empty())
{
TreeNode* node = stack.back();// or stack.top()
stack.pop_back();
swap(node->left,node->right);
if(node->left)stack.push_back(node->left);
if(node->right)stack.push_back(node->right);
}
return root;
}