二叉树的节点个数
代码实现
int count_tree(TreeNode *bt)
{
int count = 0;
if(NULL == bt){
//cout<<"tree is empty\n";
return 0;
}
queue<TreeNode *> que;
que.push(bt);
while(!que.empty()){
bt = que.front();
que.pop();
count++;
//print(bt->data);
if(bt->lchild)
que.push(bt->lchild);
if(bt->rchild)
que.push(bt->rchild);
}
return count;
}二叉树的深度
代码实现
int depth_tree(TreeNode *bt)
{
int depth = 0,count = 0;
if(NULL == bt){
cout<<"tree is empty\n";
return 0;
}
stack<TreeNode *> st;
stack<int> flag;
int first = 1,second = 2;
while(bt || !st.empty()){
while(bt){
st.push(bt);
flag.push(first);
bt = bt->lchild;
count++;
}
if(1 == flag.top()){
flag.pop();
flag.push(second);
bt = st.top();
bt = bt->rchild;
}
else{
if(count > depth)
depth = count;
while(!flag.empty() && 2 == flag.top()){
flag.pop();
bt = st.top();
st.pop();
count--;
}
bt = NULL;
}
}
return depth;
}
本文介绍了一种使用队列实现遍历的方法来计算二叉树中节点的数量,以及一种使用栈来实现先序遍历的方法来确定二叉树的深度。这两种算法都适用于完全二叉树及一般二叉树。
5249

被折叠的 条评论
为什么被折叠?



