先上题目,大概意思是给出一颗二叉树,输出叶子节点,输出的顺序是从上到下,从左往右。输入的数据,第一行表示节点个数,后面的行表示节点的数据,例如"1 -"表示序号为0的节点的左子节点为1,没有右子节点。
-----------------------------------------------------------------------------------------------------------
Given a tree, you are supposed to list all the leaves in theorder of top down, and left to right.
Input Specification:
Each input file contains one test case. For each case, the firstline gives a positive integer N (<=10) which is the total numberof nodes in the tree -- and hence the nodes are numbered from 0 toN-1. Then N lines follow, each corresponds to a node, and gives theindices of the left and right children of the node. If the childdoes not exist, a "-" will be put at the position. Any pair ofchildren are separated by a space.
Output Specification:
For each test case, print in one line all the leaves' indices inthe order of top down, and left to right. There must be exactly onespace between any adjacent numbers, and no extra space at the endof the line.
Sample Input:8 1 - - - 0 - 2 7 - - - - 5 - 4 6Sample Output:
4 1 5 -------------------------------------------------------------------------------
实现的思路
1.首先要输入二叉树,按照输入的二叉树数量大小,建立二叉树数组,数组的序号默认为节点的序号
2.找到root节点
3.采用层序遍历的方式遍历,遍历时如果发现该节点是叶子节点就输出,需要用list实现队列的功能
-------------------------------------------------------------------------------------------------------------
- package
main -
- import(
-
"fmt" -
"container/list" - )
- func
main(){ -
var N int -
_, err := fmt.Scanf("%d\n",&N) -
if err != nil { -
fmt.Println("error", err) -
} -
nodes := make([]treeNode,N) -
hasNode := make([]bool,N) -
-
var left,right int32 -
for i := 0; i -
nodes[i].data = i//赋值 -
_, err := fmt.Scanf("%c %c\n",&left,&right)//输入i号节点的左右子节点 -
if err != nil { -
fmt.Println("error", err) -
} -
if left != '-'{ -
left = left - '0' -
nodes[i].left = &nodes[left] -
hasNode[left] = true//表示该节点的引用存在 -
} -
if right != '-'{ -
right = right - '0' -
nodes[i].right = &nodes[right] -
hasNode[right] = true//表示该节点的引用存在 -
} -
} -
-
//查询根节点 -
var root int -
for i,flag := range hasNode{ -
if(flag == false){ -
root = i//找到根节点 -
} -
} -
-
ls := list.New() -
ls.PushBack(nodes[root])//压入root -
ele := ls.Front(); -
for first := true ; ele != nil;{//层序遍历 -
node := (ele.Value).(treeNode)//断言为treeNode类型,node为一棵树 -
if node.left != nil{ -
ls.PushBack(*node.left)//node.left是指向treeNode的指针,加*解引用 -
} -
if node.right != nil { -
ls.PushBack(*node.right) -
} -
//检查是否为叶子节点 -
if node.left == nil && node.right == nil{ -
if first{//如果是第一个输出的数据 -
fmt.Print(node.data) -
first = false//第一次已经没有了 -
}else{ -
fmt.Print(" ",node.data) -
} -
} -
ls.Remove(ele)//干掉它 -
ele = ls.Front(); -
-
} - }
-
- type
treeNode struct{ -
data int -
left *treeNode -
right *treeNode - }