LCR 144. 翻转二叉树 - 力扣(LeetCode)
给定一棵二叉树的根节点 root
,请左右翻转这棵二叉树,并返回其根节点。
示例 1:
输入:root = [5,7,9,8,3,2,4] 输出:[5,9,7,4,2,3,8]
提示:
- 树中节点数目范围在
[0, 100]
内 -100 <= Node.val <= 100
题解
前序遍历图解
代码
递归算法
/*** 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* mirrorTree(TreeNode* root) {if(!root) return nullptr;swap(root->left,root->right);mirrorTree(root->left);mirrorTree(root->right);return root;}
};
非递归算法
/*** 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* mirrorTree(TreeNode* root) {if(!root) return nullptr;stack<TreeNode*> s;s.push(root);while(!s.empty()){TreeNode* node=s.top();s.pop();swap(node->left,node->right);if(node->left) s.push(node->left);if(node->right) s.push(node->right);}return root;}
};