注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号 
x
You are given a description of a rooted tree. Your task is to compute and output its height. Recall
that the height of a (rooted) tree is the maximum depth of a node, or the maximum distance from a
leaf to the root. You are given an arbitrary tree, not necessarily a binary tree.
简单来说就是数组对应的下标就是自己的子节点,如果是-1的话,对应的下标就是根;
Input:
5
4 -1 4 1 1
Output:
3
Explanation:
The input means that there are 5 nodes with numbers from 0 to 4, node 0 is a child of node 4, node
1 is the root, node 2 is a child of node 4, node 3 is a child of node 1 and node 4 is a child of node 1.
The height of this tree is 3, because the number of vertices on the path from root 1 to leaf 2 is 3.
树的结构如下
1
/ \
3 4
/ \
0 2
http://www.geeksforgeeks.org/fin ... ented-parent-array/ Amazon貌似考过
跟这道题其实是一道题,但是这个树不一定只是二叉树。
这道题有很多种做法,可以不用转化成树也可以直接求解。- class BinaryTree {
-
- // This function fills depth of i'th element in parent[]. The depth is
- // filled in depth[i].
- void fillDepth(int parent[], int i, int depth[]) {
-
- // If depth[i] is already filled
- if (depth[i] != 0) {
- return;
- }
-
- // If node at index i is root
- if (parent[i] == -1) {
- depth[i] = 1;
- return;
- }
-
- // If depth of parent is not evaluated before, then evaluate
- // depth of parent first
- if (depth[parent[i]] == 0) {
- fillDepth(parent, parent[i], depth);
- }
-
- // Depth of this node is depth of parent plus 1
- depth[i] = depth[parent[i]] + 1;
- }
-
- // This function returns height of binary tree represented by
- // parent array
- int findHeight(int parent[], int n) {
-
- // Create an array to store depth of all nodes/ and
- // initialize depth of every node as 0 (an invalid
- // value). Depth of root is 1
- int depth[] = new int[n];
- for (int i = 0; i < n; i++) {
- depth[i] = 0;
- }
-
- // fill depth of all nodes
- for (int i = 0; i < n; i++) {
- fillDepth(parent, i, depth);
- }
-
- // The height of binary tree is maximum of all depths.
- // Find the maximum value in depth[] and assign it to ht.
- int ht = depth[0];
- for (int i = 1; i < n; i++) {
- if (ht < depth[i]) {
- ht = depth[i];
- }
- }
- return ht;
- }
-
- // Driver program to test above functions
- public static void main(String args[]) {
-
- BinaryTree tree = new BinaryTree();
-
- // int parent[] = {1, 5, 5, 2, 2, -1, 3};
- int parent[] = new int[]{-1, 0, 0, 1, 1, 3, 5};
-
- int n = parent.length;
- System.out.println("Height is " + tree.findHeight(parent, n));
- }
- }
复制代码 但是现在如果想用树的方法如何做呢? 构建树的结构的时候,是不是需要用一个hashmap把数字和对应的树节点联系起来,才方便调用树节点?
还有应该怎么计算非二叉树的高度呢,递归,DFS,BFS,具体如何实现呢?非常感谢!!!!
|