一、基本操作
二叉树结构
public class TreeNode
{
public int val;
public TreeNode left;
public TreeNode right;
TreeNode(int x)//构造函数
{
val=x;
}
}
前序遍历:根结点,左子树,右子树
public static void PreNode(TreeNode node,List<int> treeList)
{
if(node!=null)
{
treeList.Add(node.val);
PreNode(node.left,treeList);
PreNode(node.right,treeList);
}
}
中序遍历:左子树,根结点,右子树
public static void MidNode(TreeNode node,List<int> treeList)
{
if(node!=null)
{
MidNode(node.left,treeList);
treeList.Add(node.val);
MidNode(node.right,treeList);
}
}
后序遍历:左子树,右子树,根结点
public static void EndNode(TreeNode node,List<int> treeList)
{
if(node!=null)
{
EndNode(node.left,treeList);
EndNode(node.right,treeList);
treeList.Add(node.val);
}
}
层次遍历:借助一个队列,先将根结点入队,然后根结点出队,每个结点出队时就访问该结点,且若其子树不为空则将其子树入队,然后每一层从左往右进行入队,直到队空。
public static void LevelNode(TreeNode node,List<int> treeList)
{
if(node!=null)
{
Queue<int> queue=new Queue<TreeNode>();
queue.Enqueue(node);
TreeNode currentNode=null;
while(queue.Count>0)
{
currentNode=queue.Dequeue();
treeList.Add(currentNode.val);
if(currentNode.left!=null)
{
queue.Enqueue(currentNode.left);
}
if(currentNode.right!=null)
{
queue.Enqueue(currentNode.right);
}
}
}
}
二、其他操作
语言:C
二叉树C语言定义
//二叉树C语言定义
typedef struct Node
{
char data;
struct Node *lchild,*rchild;
}*BiTree,BiTNode;
//二叉树的复制
void Copy(BiTree &T,BiTree &NewT)
{
if(!T)
{
NewT=NULL;
return;
}
NewT=new BiTNode;
Copy(T->lchild,NewT->lchild);
Copy(T->rchild,NewT->rchild);
}
//树的深度
int Depth(BiTree T)
{
if(!T)
return 0;
int l=Depth(T->lchild);
int r=Depth(T->rchild);
return l>r?l:r+1;
}
//二叉树中的结点个数
int NodeCount(BiTree T)
{
if(!T)
return 0;
return NodeCount(T->lchild)+NodeCount(T->rchild)+1;
}
//二叉树叶子结点个数
int LeafCount(BiTree T)
{
if(!T)
return 0;
if(T->lchild==NULL&&T->rchild==NULL)
return 1;
return LeafCount(T->lchild)+LeafCount(T->rchild);
}
//二叉树度为1的结点
int Node_1_Count(BiTree T)
{
if(!T)
return 0;
if(!T->lchild&&T->rchild||T->lchild&&!T->rchild)
return 1;
return Node_1_Count(T->lchild)+Node_1_Count(T->rchild);
}
//输出从根结点到每个叶子的路径,遍历二叉树,存下每个结点值与数组长度,遇到根结点则输出路径
void Path(BiTree T,char path[],int pathlen)
{
if(!T) return;
path[pathlen]=T->data;
if(!T->lchild&&!T->rchild)
{
printf("路径")
for(int i=0;i<pathlen;i++)
printf("%c ",path[i]);
printf("\n");
}
Path(T->lchild,path,pathlen+1);
Path(T->rchild,path,pathlen+1);
}
感谢参考博客: