📜  查找父数组表示的二叉树的高度

📅  最后修改于: 2022-05-13 01:57:16.647000             🧑  作者: Mango

查找父数组表示的二叉树的高度

给定的数组表示一棵树,数组值给出了该特定索引的父节点。根节点索引的值将始终为 -1。求树的高度。
二叉树的高度是从根到最深叶节点的路径上的节点数,这个数包括根和叶。

Input: parent[] = {1 5 5 2 2 -1 3}
Output: 4
The given array represents following Binary Tree 
         5
        /  \
       1    2
      /    / \
     0    3   4
         /
        6 


Input: parent[] = {-1, 0, 0, 1, 1, 3, 5};
Output: 5
The given array represents following Binary Tree 
         0
       /   \
      1     2
     / \
    3   4
   /
  5 
 /
6

推荐:请先在“PRACTICE”上解决,然后再继续解决。

来源:亚马逊面试经历 |第 128 组(用于 SDET)
我们强烈建议您最小化您的浏览器并首先自己尝试。
一个简单的解决方案是先构造树,然后找到构造的二叉树的高度。可以通过首先搜索当前根,然后递归找到找到的索引并使它们成为根的左子树和右子树来递归地构造树。该解决方案需要 O(n 2 ),因为我们必须线性搜索每个节点。
一个有效的解决方案可以在 O(n) 时间内解决上述问题。这个想法是首先计算每个节点的深度并将其存储在数组 depth[] 中。一旦我们有了所有节点的深度,我们就会返回所有深度的最大值。
1)求所有节点的深度,填入一个辅助数组depth[]。
2) 在depth[]中返回最大值。
以下是查找索引 i 处节点深度的步骤。
1) 如果是根,depth[i] 为 1。
2) 如果计算 parent[i] 的深度,depth[i] 为 depth[parent[i]] + 1。
3) 如果没有评估 parent[i] 的深度,则为 parent 重复并将 depth[i] 分配为 depth[parent[i]] + 1(同上)。
以下是上述思想的实现。

C++
// C++ program to find height using parent array
#include 
using namespace std;
 
// 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])
        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[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
int main()
{
    // int parent[] = {1, 5, 5, 2, 2, -1, 3};
    int parent[] = { -1, 0, 0, 1, 1, 3, 5 };
 
    int n = sizeof(parent) / sizeof(parent[0]);
    cout << "Height is " << findHeight(parent, n);
    return 0;
}


Java
// Java program to find height using parent array
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));
    }
}


Python3
# Python program to find height using parent array
 
# This functio fills depth of i'th element in parent[]
# The depth is filled in depth[i]
 
 
def fillDepth(parent, i, 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
 
 
def findHeight(parent):
    n = len(parent)
    # Create an array to store depth of all nodes and
    # initialize depth of every node as 0
    # Depth of root is 1
    depth = [0 for i in range(n)]
 
    # fill depth of all nodes
    for i in range(n):
        fillDepth(parent, i, depth)
 
    # The height of binary tree is maximum of all
    # depths. Find the maximum in depth[] and assign
    # it to ht
    ht = depth[0]
    for i in range(1, n):
        ht = max(ht, depth[i])
 
    return ht
 
 
# Driver program to test above function
parent = [-1, 0, 0, 1, 1, 3, 5]
print ("Height is %d" % (findHeight(parent)))
 
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)


C#
using System;
 
// C# program to find height using parent array
public class BinaryTree {
 
    // This function fills depth of i'th element in
    // parent[].  The depth is filled in depth[i].
    public virtual 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
    public virtual 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;
        Console.WriteLine("Height is  "
                          + tree.findHeight(parent, n));
    }
}
 
// This code is contributed by Shrikant13


Javascript


Javascript


输出:

Height is 5