标签:inf oid 实现 public mirror while return null 分享图片
先把根节点的左右子树交换,再对左子树、右子树进行同样的操作。
class Solution {
public:
void Mirror(TreeNode *pRoot) {
if(pRoot == NULL)
return;
TreeNode *temp;
temp = pRoot->left;
pRoot->left = pRoot->right;
pRoot->right = temp;
Mirror(pRoot->left);
Mirror(pRoot->right);
}
};
既可以用队列辅助,也可以用栈辅助。如果用队列,先把根节点的左右子树交换,然后把左右子树入队列,每次取出队首元素,交换左右子树,直到队列为空。
class Solution {
public:
void Mirror(TreeNode *pRoot) {
if(pRoot == NULL)
return;
queue<TreeNode*> qq;
qq.push(pRoot);
TreeNode *node, *temp;
while(!qq.empty()){
node = qq.front();
temp = node->left;
node->left = node->right;
node->right = temp;
qq.pop();
if(node->left)
qq.push(node->left);
if(node->right)
qq.push(node->right);
}
}
};
如果用栈,则先把根节点的左右子树交换,然后把左右子树分别入栈,每次取栈顶元素,交换左右子树,直到栈为空。
class Solution {
public:
void Mirror(TreeNode *pRoot) {
if(pRoot == NULL)
return;
stack<TreeNode*> ss;
TreeNode *node, *temp;
ss.push(pRoot);
while(!ss.empty()){
node = ss.top();
ss.pop();
temp = node->left;
node->left = node->right;
node->right = temp;
if(node->left)
ss.push(node->left);
if(node->right)
ss.push(node->right);
}
}
};
标签:inf oid 实现 public mirror while return null 分享图片
原文地址:https://www.cnblogs.com/jiaxblog/p/9652303.html