zoukankan      html  css  js  c++  java
  • 二叉树两节点距离

     1 #include <stdio.h>
     2 
     3 typedef int ElementType;
     4 
     5 struct BinarySearchTreeNode
     6 {
     7     ElementType Element;
     8     struct BinarySearchTreeNode *Left;
     9     struct BinarySearchTreeNode *Right;
    10 };
    11 
    12 //be careful with the names of the node and struct
    13 struct BinarySearchTreeNode* BinaryTreeLCA(struct BinarySearchTreeNode* TreeRoot,struct BinarySearchTreeNode* TreeNode_1,struct BinarySearchTreeNode* TreeNode_2)
    14 {
    15     if(TreeRoot==NULL || TreeRoot==TreeNode_1 || TreeRoot==TreeNode_2)
    16     {
    17         return TreeRoot;
    18     }
    19     
    20     struct BinarySearchTreeNode* NewLeft = BinaryTreeLCA(TreeRoot -> Left,TreeNode_1,TreeNode_2);
    21     struct BinarySearchTreeNode* NewRight = BinaryTreeLCA(TreeRoot -> Right,TreeNode_1,TreeNode_2);
    22     
    23     if(NewLeft && NewRight)
    24     {
    25         return TreeRoot;
    26     }
    27     
    28     return NewLeft == NULL ? NewRight : NewLeft;
    29 }
    30 
    31 int BinarySearchTreeNodeFindLevel(struct BinarySearchTreeNode *TreeRoot,struct BinarySearchTreeNode *NodeToBeFind)
    32 {
    33     if(TreeRoot == NULL || NodeToBeFind == NULL)
    34     {
    35         return -1;
    36     }
    37     if(TreeRoot -> Element == NodeToBeFind -> Element)
    38     {
    39         return 0;
    40     }
    41     
    42     int Level = BinarySearchTreeNodeFindLevel(TreeRoot -> Left,NodeToBeFind);
    43     if(Level == -1)
    44     {
    45         Level = BinarySearchTreeNodeFindLevel(TreeRoot -> Right,NodeToBeFind);
    46     }
    47     if(Level != -1)
    48     {
    49         return (Level+1);
    50     }
    51     return -1;
    52 }
    53 
    54 int BinarySearchTreeNodeDistance(struct BinarySearchTreeNode* TreeRoot,struct BinarySearchTreeNode* TreeNode_1,struct BinarySearchTreeNode* TreeNode_2)
    55 {
    56     struct BinarySearchTreeNode* TwoNodeLCA = BinaryTreeLCA(TreeRoot,TreeNode_1,TreeNode_2);
    57     
    58     int LCADistance = BinarySearchTreeNodeFindLevel(TreeRoot,TwoNodeLCA);
    59     int Node_1Distance = BinarySearchTreeNodeFindLevel(TreeRoot,TreeNode_1);
    60     int Node_2Distance = BinarySearchTreeNodeFindLevel(TreeRoot,TreeNode_2);
    61     
    62     return (Node_1Distance + Node_2Distance - 2 * LCADistance);
    63 }
    64 
    65 int main()
    66 {
    67     //int result = BinarySearchTreeNodeDistance(TreeRoot,BinarySearchTreeNodeFind(-1,TreeRoot),BinarySearchTreeNodeFind(-1,TreeRoot));
    68     //printf("%d
    ",result);
    69     return 0;
    70 }
  • 相关阅读:
    innerHTML使用方法
    HDU 1426 Sudoku Killer
    Junit使用教程(一)
    HLS协议实现
    GPIO
    TraceView总结
    在kettle中实现数据验证和检查
    用户向导左右滑动页面实现之ImageSwitcher
    DWZ使用笔记
    oracle进程
  • 原文地址:https://www.cnblogs.com/Asurudo/p/9427469.html
Copyright © 2011-2022 走看看