📜  给定二叉树的最长笔直路径的长度

📅  最后修改于: 2021-05-04 11:52:37             🧑  作者: Mango

给定二叉树,任务是找到给定二叉树的最长笔直路径的长度。

例子:

方法:想法是使用后置遍历。请按照以下步骤解决问题:

  1. 对于每个节点,请检查当前节点的方向(向左或向右),并检查其子节点的哪个方向向该节点提供其下方最长的长度。
  2. 如果当前节点的方向与给出最长长度的子节点的方向不同,则保存该子节点的结果,并将另一个子节点的长度传递给其父节点。
  3. 使用上述步骤,可以找到每个节点上最长的直线路径,并保存结果以在所有直线路径中打印出最大值
  4. 完成上述步骤后,打印最大路径。

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Structure of a Tree node
struct Node {
    int key;
    struct Node *left, *right;
};
 
// Function to create a new node
Node* newNode(int key)
{
    Node* temp = new Node;
    temp->key = key;
    temp->left = temp->right = NULL;
    return (temp);
}
 
// Function to find the longest
// straight path in a tree
int findPath(Node* root, char name,
             int& max_v)
{
    // Base Case
    if (root == NULL) {
        return 0;
    }
 
    // Recursive call on left child
    int left = findPath(root->left,
                        'l', max_v);
 
    // Recursive call on right child
    int right = findPath(root->right,
                         'r', max_v);
 
    // Return the maximum straight
    // path possible from current node
    if (name == 't') {
        return max(left, right);
    }
 
    // Leaf node
    if (left == 0 && right == 0) {
        return 1;
    }
 
    // Executes when either of the
    // child is present or both
    else {
 
        // Pass the longest value from
        // either direction
        if (left < right) {
            if (name == 'r')
                return 1 + right;
 
            else {
                max_v = max(max_v, right);
                return 1 + left;
            }
        }
        else {
            if (name == 'l')
                return 1 + left;
 
            else {
                max_v = max(max_v, left);
                return 1 + right;
            }
        }
    }
    return 0;
}
 
// Driver Code
int main()
{
 
    // Given Tree
    Node* root = newNode(3);
 
    root->left = newNode(3);
    root->right = newNode(3);
 
    root->left->right = newNode(2);
    root->right->left = newNode(4);
    root->right->left->left = newNode(4);
 
    int max_v = max(
        findPath(root, 't', max_v),
        max_v);
 
    // Print the maximum length
    cout << max_v << "\n";
}


Java
// Java program for the above approach
import java.util.*;
 
class GFG{
     
static int max_v;
 
// Structure of a Tree node
static class Node
{
    int key;
    Node left, right;
};
 
// Function to create a new node
static Node newNode(int key)
{
    Node temp = new Node();
    temp.key = key;
    temp.left = temp.right = null;
    return (temp);
}
 
// Function to find the longest
// straight path in a tree
static int findPath(Node root, char name)
{
     
    // Base Case
    if (root == null)
    {
        return 0;
    }
 
    // Recursive call on left child
    int left = findPath(root.left, 'l');
 
    // Recursive call on right child
    int right = findPath(root.right, 'r');
 
    // Return the maximum straight
    // path possible from current node
    if (name == 't')
    {
        return Math.max(left, right);
    }
 
    // Leaf node
    if (left == 0 && right == 0)
    {
        return 1;
    }
 
    // Executes when either of the
    // child is present or both
    else
    {
         
        // Pass the longest value from
        // either direction
        if (left < right)
        {
            if (name == 'r')
                return 1 + right;
            else
            {
                max_v = Math.max(max_v, right);
                return 1 + left;
            }
        }
        else
        {
            if (name == 'l')
                return 1 + left;
            else
            {
                max_v = Math.max(max_v, left);
                return 1 + right;
            }
        }
    }
}
 
// Driver Code
public static void main(String[] args)
{
 
    // Given Tree
    Node root = newNode(3);
 
    root.left = newNode(3);
    root.right = newNode(3);
    root.left.right = newNode(2);
    root.right.left = newNode(4);
    root.right.left.left = newNode(4);
 
    max_v = Math.max(findPath(root, 't'),
                     max_v);
 
    // Print the maximum length
    System.out.print(max_v+ "\n");
}
}
 
// This code is contributed by Amit Katiyar


Python3
# Python3 program for the above approach
max_v = 0
 
# Structure of a Tree node
class newNode:
     
    def __init__(self, key):
         
        self.key = key
        self.left = None
        self.right = None
 
# Function to find the longest
# straight path in a tree
def findPath(root, name):
     
    global max_v
     
    # Base Case
    if (root == None):
        return 0
 
    # Recursive call on left child
    left = findPath(root.left, 'l')
 
    # Recursive call on right child
    right = findPath(root.right, 'r')
     
    # Return the maximum straight
    # path possible from current node
    if (name == 't'):
        return max(left, right)
 
    # Leaf node
    if (left == 0 and right == 0):
        return 1
 
    # Executes when either of the
    # child is present or both
    else:
         
        # Pass the longest value from
        # either direction
        if (left < right):
            if (name == 'r'):
                return 1 + right
            else:
                max_v = max(max_v, right)
                return 1 + left
        else:
            if (name == 'l'):
                return 1 + left
            else:
                max_v = max(max_v, left)
                return 1 + right
                 
    return 0
 
def helper(root):
     
    global max_v
    temp = max(findPath(root, 't'), max_v)
    print(temp)
 
# Driver Code
if __name__ == '__main__':
     
    # Given Tree
    root = newNode(3)
    root.left = newNode(3)
    root.right = newNode(3)
    root.left.right = newNode(2)
    root.right.left = newNode(4)
    root.right.left.left = newNode(4)
     
    helper(root)
 
# This code is contributed by ipg2016107


C#
// C# program for
// the above approach
using System;
class GFG{
     
static int max_v;
 
// Structure of a Tree node
public class Node
{
  public int key;
  public Node left, right;
};
 
// Function to create a new node
static Node newNode(int key)
{
  Node temp = new Node();
  temp.key = key;
  temp.left = temp.right = null;
  return (temp);
}
 
// Function to find the longest
// straight path in a tree
static int findPath(Node root,
                    char name)
{
  // Base Case
  if (root == null)
  {
    return 0;
  }
 
  // Recursive call on left child
  int left = findPath(root.left, 'l');
 
  // Recursive call on right child
  int right = findPath(root.right, 'r');
 
  // Return the maximum straight
  // path possible from current node
  if (name == 't')
  {
    return Math.Max(left, right);
  }
 
  // Leaf node
  if (left == 0 && right == 0)
  {
    return 1;
  }
 
  // Executes when either of the
  // child is present or both
  else
  {
    // Pass the longest value from
    // either direction
    if (left < right)
    {
      if (name == 'r')
        return 1 + right;
      else
      {
        max_v = Math.Max(max_v, right);
        return 1 + left;
      }
    }
    else
    {
      if (name == 'l')
        return 1 + left;
      else
      {
        max_v = Math.Max(max_v, left);
        return 1 + right;
      }
    }
  }
}
 
// Driver Code
public static void Main(String[] args)
{
  // Given Tree
  Node root = newNode(3);
 
  root.left = newNode(3);
  root.right = newNode(3);
  root.left.right = newNode(2);
  root.right.left = newNode(4);
  root.right.left.left = newNode(4);
 
  max_v = Math.Max(findPath(root, 't'), max_v);
 
  // Print the maximum length
  Console.Write(max_v + "\n");
}
}
 
// This code is contributed by 29AjayKumar


输出:
2








时间复杂度: O(N)
辅助空间: O(1)