标签:优先 read alt adf bre 辅助 技术分享 搜索 ret
1、把根节点入队列;
2、如果队列非空,出队,再依次将左子树入队、右子树入队;
3、重复步骤2,直到队列为空。
void BreadFirstSearch(TreeNode *root){
if(root == NULL)
return;
queue<TreeNode*> q;
q.push(root);
TreeNode* node;
while(!q.empty()){
node = q.front();
cout << node->val << " ";
q.pop();
if(node->left)
q.push(node->left);
if(node->right)
q.push(node->right);
}
}
1、把根节点入栈;
2、如果栈非空,则出栈,再依次将右子树入栈、左子树入栈;
3、重复步骤2,直到栈为空。
void DepthFirtstSearch(TreeNode* root){
if(root == NULL)
return;
stack<TreeNode*> ss;
ss.push(root);
TreeNode* node;
while(!ss.empty()){
node = ss.top();
cout << ss->val << " ";
ss.pop();
if(node->right)
ss.push(node->right);
if(node->left)
ss.push(node->left);
}
}
方法1:递归实现,先把根节点的左右子树交换,再对左子树、右子树进行同样的操作。
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);
}
};
方法2:非递归,既可以用队列辅助,也可以用栈辅助。如果用队列,先把根节点的左右子树交换,然后把左右子树入队列,每次取出队首元素,交换左右子树,直到队列为空。
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);
}
}
};
标签:优先 read alt adf bre 辅助 技术分享 搜索 ret
原文地址:https://www.cnblogs.com/jiaxblog/p/9649513.html