📜  O(n)中二叉树的直径[一种新方法]

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

O(n)中二叉树的直径[一种新方法]

树的直径是树中两片叶子之间最长路径上的节点数。下图显示了两棵直径为 9 的树,形成最长路径末端的叶子是彩色的(请注意,相同直径的树中可能有不止一条路径)。

例子:

Input :     1
          /   \
        2      3
      /  \
    4     5

Output : 4

Input :     1
          /   \
        2      3
      /  \ .    \
    4     5 .    6

Output : 5

我们在下面的帖子中讨论了一个解决方案。
二叉树的直径
在这篇文章中,我们讨论了一种新的简单 O(n) 方法。树的直径只能通过height函数来计算,因为树的直径只不过是每个节点的(left_height + right_height + 1)的最大值。所以我们需要为每个节点计算这个值(left_height + right_height + 1)并更新结果。时间复杂度 - O(n)

C++
// Simple C++ program to find diameter
// of a binary tree.
#include 
using namespace std;
 
/* Tree node structure used in the program */
struct Node {
    int data;
    Node* left, *right;
};
 
/* Function to find height of a tree */
int height(Node* root, int& ans)
{
    if (root == NULL)
        return 0;
 
    int left_height = height(root->left, ans);
 
    int right_height = height(root->right, ans);
 
    // update the answer, because diameter of a
    // tree is nothing but maximum value of
    // (left_height + right_height + 1) for each node
    ans = max(ans, 1 + left_height + right_height);
 
    return 1 + max(left_height, right_height);
}
 
/* Computes the diameter of binary tree with given root. */
int diameter(Node* root)
{
    if (root == NULL)
        return 0;
    int ans = INT_MIN; // This will store the final answer
    height(root, ans);
    return ans;
}
 
struct Node* newNode(int data)
{
    struct Node* node = new Node;
    node->data = data;
    node->left = node->right = NULL;
 
    return (node);
}
 
// Driver code
int main()
{
    struct Node* root = newNode(1);
    root->left = newNode(2);
    root->right = newNode(3);
    root->left->left = newNode(4);
    root->left->right = newNode(5);
 
    printf("Diameter is %d\n", diameter(root));
 
    return 0;
}


Java
// Simple Java program to find diameter
// of a binary tree.
class GfG {
 
/* Tree node structure used in the program */
static class Node
{
    int data;
    Node left, right;
}
 
static class A
{
    int ans = Integer.MIN_VALUE;
}
 
/* Function to find height of a tree */
static int height(Node root, A a)
{
    if (root == null)
        return 0;
 
    int left_height = height(root.left, a);
 
    int right_height = height(root.right, a);
 
    // update the answer, because diameter of a
    // tree is nothing but maximum value of
    // (left_height + right_height + 1) for each node
    a.ans = Math.max(a.ans, 1 + left_height +
                    right_height);
 
    return 1 + Math.max(left_height, right_height);
}
 
/* Computes the diameter of binary
tree with given root. */
static int diameter(Node root)
{
    if (root == null)
        return 0;
 
    // This will store the final answer
    A a = new A();
    int height_of_tree = height(root, a);
    return a.ans;
}
 
static Node newNode(int data)
{
    Node node = new Node();
    node.data = data;
    node.left = null;
    node.right = null;
 
    return (node);
}
 
// Driver code
public static void main(String[] args)
{
    Node root = newNode(1);
    root.left = newNode(2);
    root.right = newNode(3);
    root.left.left = newNode(4);
    root.left.right = newNode(5);
 
    System.out.println("Diameter is " + diameter(root));
}
}
 
// This code is contributed by Prerna Saini.


Python3
# Simple Python3 program to find diameter
# of a binary tree.
 
class newNode:
    def __init__(self, data):
        self.data = data
        self.left = self.right = None
 
# Function to find height of a tree
def height(root, ans):
    if (root == None):
        return 0
 
    left_height = height(root.left, ans)
 
    right_height = height(root.right, ans)
 
    # update the answer, because diameter
    # of a tree is nothing but maximum
    # value of (left_height + right_height + 1)
    # for each node
    ans[0] = max(ans[0], 1 + left_height +
                             right_height)
 
    return 1 + max(left_height,
                   right_height)
 
# Computes the diameter of binary
# tree with given root.
def diameter(root):
    if (root == None):
        return 0
    ans = [-999999999999] # This will store
                          # the final answer
    height_of_tree = height(root, ans)
    return ans[0]
 
# Driver code
if __name__ == '__main__':
    root = newNode(1)
    root.left = newNode(2)
    root.right = newNode(3)
    root.left.left = newNode(4)
    root.left.right = newNode(5)
 
    print("Diameter is", diameter(root))
 
# This code is contributed by PranchalK


C#
// Simple C# program to find diameter
// of a binary tree.
using System;
 
class GfG
{
 
/* Tree node structure used in the program */
class Node
{
    public int data;
    public Node left, right;
}
 
class A
{
    public int ans = int.MinValue;
}
 
/* Function to find height of a tree */
static int height(Node root, A a)
{
    if (root == null)
        return 0;
 
    int left_height = height(root.left, a);
 
    int right_height = height(root.right, a);
 
    // update the answer, because diameter of a
    // tree is nothing but maximum value of
    // (left_height + right_height + 1) for each node
    a.ans = Math.Max(a.ans, 1 + left_height +
                    right_height);
 
    return 1 + Math.Max(left_height, right_height);
}
 
/* Computes the diameter of binary
tree with given root. */
static int diameter(Node root)
{
    if (root == null)
        return 0;
 
    // This will store the final answer
    A a = new A();
    int height_of_tree = height(root, a);
    return a.ans;
}
 
static Node newNode(int data)
{
    Node node = new Node();
    node.data = data;
    node.left = null;
    node.right = null;
 
    return (node);
}
 
// Driver code
public static void Main()
{
    Node root = newNode(1);
    root.left = newNode(2);
    root.right = newNode(3);
    root.left.left = newNode(4);
    root.left.right = newNode(5);
 
    Console.WriteLine("Diameter is " + diameter(root));
}
}
 
/* This code is contributed by Rajput-Ji*/


Javascript


输出
Diameter is 4