求二叉树的深度算法 #include <iostream> #include <stack> using namespace std; struct BinTree { int data; BinTree *lc; BinTree *rc; }BTNode,*BinTree; int max(int a,int b) { return (a>b)?a:b; } int BinTreeDepth(BinTree T) { stack<BinTree> s; BinTree p = T,r = NULL; int depth=0; while(p||!s.empty()) { if(p) { //从根节点向左边走 s.push(p); int size = s.size();//获取栈的大小 depth = max(depth,size);//替换最大值 p = p->lc; } else { //左边走不通向右走 p = s.top(); if(p->rc&&p->rc!=r)//如果右子树存在,且未被访问过 { p = p->rc; s.push(p); int size = s.size();//获取栈的大小 depth = max(depth,size);//替换最大值 p = p->lc; }else { p=s.top(); s.pop(); cout<<p->data<<endl; r=p; //记录最近访问的节点 p=NULL; //节点访问完之后,重置p指针,目的是为了防止再次将左孩子压栈 } } } return depth; } 求二叉树深度的算法
int height(Bitree T) { if (T==NULL) return 0; u=height(T->lchild); v=height(T->rchild); if (u>n) return (u+1) return (v+1) }
procedure tree(a:node,depth:integer); begin if result<depth then result:=depth; if a.leftchild<>nil then tree(a.leftchild,depth+1); if a.rightchild<>nil then tree(a.rightchild,depth+1); end; 注:result是全局变量,是结果 int depth(node *bt) { if (bt==NULL) return 0; ldepth=depth(bt->left)+1; rdepth=depth(bt->right)+1; return max(ldepth,rdepth); }
int Height(BiTree T){ int m,n; if(!T) return(0); else m=Height(T->lchild); n=Height(T->rchild); return((m>n?m:n)+1); }
// struct bnode{struct bnode *lc,*rc); int depth(struct bnode *r) { return r==NULL?0:1+max(depth(r->lc),depth(r->rc)); } 问:设计算法求二叉树的深度 #include <stdio.h> #include <stdlib.h> typedef struct node { char data; struct node *left,*right; }Node,*PNode; PNode createBtree(PNode root)//创建二叉树,控制台下输入,基于先序遍历输入 { char data; scanf("%c",&data); if (data==' ') { root=NULL; return root; } root = (PNode)malloc(sizeof(Node)); root->data = data; root->left = createBtree(root->left); root->right = createBtree(root->right); return root; } int depth(PNode root)//这就是你要的函数。 { int ld,rd; if (root==NULL) { return 0; } ld = 1+depth(root->left); rd = 1+depth(root->right); return ld>rd?ld:rd; } int main() { PNode root=NULL; root = createBtree(root); printf("%d",depth(root)); return 0; }
|