给你一棵二叉树的根节点 root ,翻转这棵二叉树,并返回其根节点。
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(root==nullptr) return nullptr;
else{
TreeNode *node = root->left;
root->left = root->right;
root->right = node;
}
root->left = invertTree(root->left);
root->right = invertTree(root->right);
return root;
}
TreeNode* invertTree(TreeNode* root) {
if (root == NULL) return root;
stack<TreeNode*> st;
st.push(root);
while(!st.empty()) {
TreeNode* node = st.top(); // 中
st.pop();
swap(node->left, node->right);
if(node->right) st.push(node->right); // 右
if(node->left) st.push(node->left); // 左
}
return root;
}
};
标签:node,right,TreeNode,st,二叉树,226,left,root,翻转
From: https://www.cnblogs.com/lihaoxiang/p/17281167.html