Initial state: enqueue root and enqueue NULL (use NULL to record all current level nodes have marked)
Iterative state:
dequeue front node v
for all edges from v to w in G.adjacentEdges(v) exist
enqueue child node w
if v is NULL, then depth++
if q is not empty, enqueue NULL
else return depth
intmaxDepth(TreeNode *root){
std::queue<TreeNode*> q;
int depth =0;
if(root){
q.push(root);
q.push(NULL);
}
while(!q.empty()){
// Pop first element from queue.
auto v = q.front();
q.pop();
// Push children to queue.
if(v){
if(v->left)
q.push(v->left);
if(v->right)
q.push(v->right);
}
// Current level nodes have traversed.
// Advance to next level.
else{
depth++;
// if queue is empty, mean this is bottom.
if(!q.empty())
q.push(NULL);
}
}
return depth;
}
BFS 解刪除 binary 指定結點,只要新增 18 ~ 27 行。
// Find the node with value equal to target.
// If you found it, delete that node and its children.
intdeleteNode(TreeNode *root,int target){
std::queue<TreeNode*> q;
int level =0;
int cur_count;
if(root){
q.push(root);
cur_count =1;
}
while(!q.empty()){
auto ptr = q.front();
q.pop();
cur_count--;
// Add this.
if(ptr->left && ptr->left->value == target){
ptr->left =nullptr;
break;
}
// Add this.
if(ptr->right && ptr->right->value == target){
ptr->right =nullptr;
break;
}
if(ptr->left){
q.push(ptr->left);
}
if(ptr->right){
q.push(ptr->right);
}
if(cur_count ==0){
cur_count = q.size();
level++;
}
}
return level;
}