Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 给定一棵二叉树,找出同一级别上两个节点之间的水平距离,同时计算节点不存在的位置_Java_Algorithm_Data Structures_Tree_Binary Tree - Fatal编程技术网

Java 给定一棵二叉树,找出同一级别上两个节点之间的水平距离,同时计算节点不存在的位置

Java 给定一棵二叉树,找出同一级别上两个节点之间的水平距离,同时计算节点不存在的位置,java,algorithm,data-structures,tree,binary-tree,Java,Algorithm,Data Structures,Tree,Binary Tree,让我非常清楚,am没有得到水平距离是多少 但还是从我的角度来看。水平距离是指:在同一级别的给定节点之间缺少或存在节点 在我的例子中,当我试图找出7和1之间的距离时,我得到了输出,即2。这就是为什么我会这样想 但是如果我试图找出9和6之间的距离,我得到的输出是4 例如,在给定树中,处于同一级别的节点7和1之间的距离为2 (考虑节点2的右子节点和节点3的左子节点) 这张图片将帮助你理解 下面是我用来检查距离的代码 public class BinaryHorizontalDistance {

让我非常清楚,am没有得到水平距离是多少

但还是从我的角度来看。水平距离是指:在同一级别的给定节点之间缺少或存在节点

在我的例子中,当我试图找出
7
1
之间的距离时,我得到了输出,即2。这就是为什么我会这样想

但是如果我试图找出
9
6
之间的距离,我得到的输出是4

例如,在给定树中,处于同一级别的节点7和1之间的距离为2 (考虑节点2的右子节点和节点3的左子节点)

这张图片将帮助你理解

下面是我用来检查距离的代码

    public class BinaryHorizontalDistance
{
    public int findDistance(Node root, int n1, int n2) 
    {

    int leftNodeToRootNode = Pathlength(root, n1, "leftNodeToRootNode") - 2;
    int rightNodeToRootNode = Pathlength(root, n2,"rightNodeToRootNode") - 2;
    int lcaData = findLCA(root, n1, n2).data;   //LCA->Lowest Common Ancestor
    int lcaDistance = Pathlength(root, lcaData,"lcaDistance") - 1;
    return (leftNodeToRootNode + rightNodeToRootNode) - 2 * lcaDistance;

    }

    public int Pathlength(Node root, int n1,String callingFrom) 
    {

    if (root != null) 
    {

        int x = 0;

        if("rightNodeToRootNode" == callingFrom)
        {

            if(root.left ==null && root.right ==null)
            {
                //do nothing

            }
            else if(root.left ==null || root.right ==null)
            {
                System.out.println("counting the position where the node is not present is : "   +   root.data);
            }
            if ((root.data == n1) || (x = Pathlength(root.left, 
               n1,"rightNodeToRootNode")) > 0  || (x = Pathlength(root.right, 
               n1,"rightNodeToRootNode")) > 0) 
            {
                return x + 1;
            }
        }
        if("rightNodeToRootNode" != callingFrom )
        {

            if ((root.data == n1) || (x = Pathlength(root.left, 
            n1,"leftNodeToRootNode")) > 0  || (x = Pathlength(root.right, 
            n1,"leftNodeToRootNode")) > 0) 
            {
                return x + 1;
            }
        }

        return 0;
    }
    return 0;
}

public Node findLCA(Node root, int n1, int n2) 
{

    if (root != null)
    {

        if (root.data == n1 || root.data == n2) 
        {
            return root;
        }
        Node left = findLCA(root.left, n1, n2);
        Node right = findLCA(root.right, n1, n2);

        if (left != null && right != null)
        {
            return root;
        }
        if (left != null) 
        {
            return left;
        }
        if (right != null)
        {
            return right;
        }
    }
    return null;
}

public static void main(String[] args) throws java.lang.Exception 
{

    Node root = new Node(5);
    root.right = new Node(2);
    root.left = new Node(3);
    root.right.right = new Node(7);
    //root.right.left = new Node(78);
    root.right.right.right = new Node(9);
    root.left.left = new Node(1);
    //root.left.right = new Node(22);
    root.left.left.right = new Node(4);
    root.left.left.left = new Node(6);

    BinaryHorizontalDistance binaryTreeTest = new BinaryHorizontalDistance();
    System.out.println("Distance between 7 and 1 is : " + 
    binaryTreeTest.findDistance(root,9, 6));
    }

}

class Node 
{
int data;
Node left;
Node right;

    public Node(int data) 
    {
    this.data = data;
    this.left = null;
    this.right = null;
    }
}

请举例说明。很高兴进一步解释

您知道以下定义:

  • 如果你是一个左撇子:计数-1
  • 如果您是正确的孩子:计数+1
这里,计算
h(4,6)

  • 4是5岁以下的孩子:-1
  • 6是5的正确孩子:+1
h(4,6)=0

这里,要计算
h(2,6)
2
4的子节点(**显然,如果节点是唯一的子节点,则必须将其视为右子节点):

所以
h(2,4)=+1
recall
h(4,6)=0
所以
h(2,6)=1

关于你的一个例子,说
h(9,6)

**我认为选择+1是为了保持一致性,但我只是观察了Python中的代码

"""
Given a binary tree, find the horizontal distance between 2 nodes at the same level, also counting the position where the node is not present.
"""
# binary tree node
class Node:
    # Constructor to create new node
    def __init__(self, data):
        self.data = data
        self.left = self.right = None
        self.val = data
    
# This function returns pointer to LCA of  two given values n1 and n2.
def LCA(root, n1, n2):    
    # Base case
    if root is None:
        return None
 
    # If either n1 or n2 matches with root's
    # key, report the presence by returning
    # root 
    if root.data == n1 or root.data == n2:
        return root
    if root.data == None or root.data == None:
        return None
 
    # Look for keys in left and right subtrees
    left = LCA(root.left, n1, n2)
    right = LCA(root.right, n1, n2)
 
    if left is not None and right is not None:
        return root
 
    # Otherwise check if left subtree or 
    # right subtree is LCA
    if left:
        return left
    else:
        return right
    
# function to find distance of any node
# from root
def findLevel(root, data, d, level):
     
    # Base case when tree is empty
    if root is None:
        return
 
    # Node is found then append level
    # value to list and return
    if root.data == data:
        d.append(level)
        return
    findLevel(root.left, data, d, level + 1)
    findLevel(root.right, data, d, level + 1)
    
# function to find distance between two
# nodes in a binary tree
def findDistance(root, n1, n2):
     
    lca = LCA(root, n1, n2)
     
    # to store distance of n1 from lca
    d1 = [] 
     
    # to store distance of n2 from lca
    d2 = [] 
 
    # if lca exist
    if lca:
         
        # distance of n1 from lca
        findLevel(lca, n1, d1, 0) 
        # print(d1)
         
        # distance of n2 from lca
        findLevel(lca, n2, d2, 0) 
        # print(d2)
        return d1[0] 
    else:
        return -1
    

def inorder(root):
    

    if root:
        # Traverse left
        
        inorder(root.left)
        # Traverse root
    
        ls.append(root.val)
            
        # print(str(root.val) + "->", end='')
        # Traverse right
        inorder(root.right) 

def height(root):
    if root:
        return 1+max(height(root.left), height(root.right))
    else:
        return -1
   
# Driver program to test above function


root = Node(5)
root1 = root.val
root.left = Node(3)
root.right = Node(2)
root.left.left = Node(1)
root.left.left.left = Node(6)
root.left.left.right = Node(4)
root.right.right= Node(7)
root.right.right.right= Node(9)

# print("Height of the Binary Tree: ", height(root))
treeHeight = height(root)


# Total nodes required to compelete binary tree
totalNodes = 2**(treeHeight + 1) -1

# print("Required Nodes : ",2**(treeHeight + 1) -1)

ls =[]
# print("Inorder traversal ")
inorder(root)

index = ls.index(root1)

treeLeft =[]
treeRight = []
for i in range(len(ls)):
    if i < index:
        treeLeft.append(ls[i])
    elif i == index:
        pass
    else:
        treeRight.append(ls[i])

print("Nodes at Same Level and horizontal distance between 2 nodes ")
print()
print("---**---**---**---**---**---**---**---**---**---**---**---**---**---")
print()
for i in treeLeft:
    for j in treeRight:
    #     print("Dist(",i,root1,") = ", findDistance(root, i, root1))
    #     print("Dist(",root1,j,") = ", findDistance(root, j, root1))
        
      
        if findDistance(root, i, root1) == findDistance(root, j, root1):
            print("Nodes are : (",i,",",j, ")  &  Horizontal Distance between (",i,",",j,"): ", findDistance(root, i, root1))
print()
print("---**---**---**---**---**---**---**---**---**---**---**---**---**---")
print()
print("count of the position where the node is not present : ", totalNodes - len(ls))
print()
print("---**---**---**---**---**---**---**---**---**---**---**---**---**---")


"""
Program Output : 
Nodes at Same Level and horizontal distance between 2 nodes 

---**---**---**---**---**---**---**---**---**---**---**---**---**---

Nodes are : ( 6 , 9 )  &  Horizontal Distance between ( 6 , 9 ):  3
Nodes are : ( 1 , 7 )  &  Horizontal Distance between ( 1 , 7 ):  2
Nodes are : ( 4 , 9 )  &  Horizontal Distance between ( 4 , 9 ):  3
Nodes are : ( 3 , 2 )  &  Horizontal Distance between ( 3 , 2 ):  1

---**---**---**---**---**---**---**---**---**---**---**---**---**---

count of the position where the node is not present :  7

---**---**---**---**---**---**---**---**---**---**---**---**---**---
"""
“”“
给定一棵二叉树,找出同一级别上两个节点之间的水平距离,同时计算节点不存在的位置。
"""
#二叉树节点
类节点:
#用于创建新节点的构造函数
定义初始化(自身,数据):
self.data=数据
self.left=self.right=无
self.val=数据
#此函数返回指向两个给定值n1和n2的LCA的指针。
def LCA(根、n1、n2):
#基本情况
如果root为None:
一无所获
#如果n1或n2与根匹配
#键,通过返回来报告存在
#根
如果root.data==n1或root.data==n2:
返回根
如果root.data==无或root.data==无:
一无所获
#在左子树和右子树中查找关键点
左=LCA(根左,n1,n2)
右=LCA(根,右,n1,n2)
如果“左”不是“无”,而“右”不是“无”:
返回根
#否则,请检查左子树或
#右子树是LCA
如果留下:
左转
其他:
返回权
#函数查找任意节点的距离
#从根本上
def findLevel(根、数据、d、级别):
#树为空时的基本情况
如果root为None:
返回
#找到节点,然后追加级别
#要列出并返回的值
如果root.data==数据:
d、 附加(级别)
返回
findLevel(root.left,数据,d,级别+1)
findLevel(root.right,数据,d,级别+1)
#函数查找两个对象之间的距离
#二叉树中的节点
def FindInstance(根、n1、n2):
lca=lca(根,n1,n2)
#存储n1与lca之间的距离
d1=[]
#储存氮气与lca之间的距离
d2=[]
#如果存在生命周期评价
如果是生命周期评价:
#n1与lca的距离
findLevel(生命周期评价,n1,d1,0)
#印刷品(d1)
#n2与lca的距离
findLevel(生命周期评价,n2,d2,0)
#印刷品(d2)
返回d1[0]
其他:
返回-1
def索引(根):
如果根:
#向左移动
顺序(根.左)
#横移根
ls.append(root.val)
#打印(str(root.val)+“->”,end='')
#导线权
顺序(root.right)
def高度(根):
如果根:
返回1+最大值(高度(根左),高度(根右))
其他:
返回-1
#用于测试上述功能的驱动程序
根=节点(5)
root1=root.val
root.left=节点(3)
root.right=节点(2)
root.left.left=节点(1)
root.left.left.left=节点(6)
root.left.left.right=节点(4)
root.right.right=节点(7)
root.right.right.right=节点(9)
#打印(“二叉树的高度:,高度(根))
树高=高度(根)
#完成二叉树所需的总节点数
totalNodes=2**(树高+1)-1
#打印(“必需节点:”,2**(树高+1)-1)
ls=[]
#打印(“按顺序遍历”)
顺序(根)
index=ls.index(root1)
treeLeft=[]
treeRight=[]
对于范围内的i(len(ls)):
如果i<索引:
treeLeft.append(ls[i])
elif i==索引:
通过
其他:
treerRight.append(ls[i])
打印(“同一级别的节点和两个节点之间的水平距离”)
打印()
打印(“--***--***--***--***--***--***--***--***--***--***--***--***--***--***--***--***--***--”)
打印()
对于我在treeLeft:
对于树右中的j:
#打印(“Dist(“,i,root1,”)=”,FindInstance(root,i,root1))
#打印(“Dist(“,root1,j,”)=”,findInstance(root,j,root1))
如果FindInstance(root,i,root1)=FindInstance(root,j,root1):
打印(“节点是:(“,i,”,“,j)”)和(“,i,”,“,j,”):”,FindInstance(根,i,根1))之间的水平距离
打印()
打印(“--***--***--***--***--***--***--***--***--***--***--***--***--***--***--***--***--***--”)
打印()
打印(“节点不存在的位置计数:”,totalNodes-len(ls))
打印()
打印(“--***--***--***--***--***--***--***--***--***--***--***--***--***--***--***--***--***--”)
"""
程序输出:
同一级别的节点和两个节点之间的水平距离
---**---**---**---**---**---**---**---**---**---**---**---**---**---
节点是:(6,9)&和(6,9)之间的水平距离:3
节点是:(1,7)&和(1,7)之间的水平距离:2
节点是:(4,9)和水平线
        5
      /   \
     4     6
      \ 
       2
h(9,7) = 2
h(2,3) = 0
h(3,1) = 1 (1 only child so +1)
h(1,6) = 1 (same)
total: 4
"""
Given a binary tree, find the horizontal distance between 2 nodes at the same level, also counting the position where the node is not present.
"""
# binary tree node
class Node:
    # Constructor to create new node
    def __init__(self, data):
        self.data = data
        self.left = self.right = None
        self.val = data
    
# This function returns pointer to LCA of  two given values n1 and n2.
def LCA(root, n1, n2):    
    # Base case
    if root is None:
        return None
 
    # If either n1 or n2 matches with root's
    # key, report the presence by returning
    # root 
    if root.data == n1 or root.data == n2:
        return root
    if root.data == None or root.data == None:
        return None
 
    # Look for keys in left and right subtrees
    left = LCA(root.left, n1, n2)
    right = LCA(root.right, n1, n2)
 
    if left is not None and right is not None:
        return root
 
    # Otherwise check if left subtree or 
    # right subtree is LCA
    if left:
        return left
    else:
        return right
    
# function to find distance of any node
# from root
def findLevel(root, data, d, level):
     
    # Base case when tree is empty
    if root is None:
        return
 
    # Node is found then append level
    # value to list and return
    if root.data == data:
        d.append(level)
        return
    findLevel(root.left, data, d, level + 1)
    findLevel(root.right, data, d, level + 1)
    
# function to find distance between two
# nodes in a binary tree
def findDistance(root, n1, n2):
     
    lca = LCA(root, n1, n2)
     
    # to store distance of n1 from lca
    d1 = [] 
     
    # to store distance of n2 from lca
    d2 = [] 
 
    # if lca exist
    if lca:
         
        # distance of n1 from lca
        findLevel(lca, n1, d1, 0) 
        # print(d1)
         
        # distance of n2 from lca
        findLevel(lca, n2, d2, 0) 
        # print(d2)
        return d1[0] 
    else:
        return -1
    

def inorder(root):
    

    if root:
        # Traverse left
        
        inorder(root.left)
        # Traverse root
    
        ls.append(root.val)
            
        # print(str(root.val) + "->", end='')
        # Traverse right
        inorder(root.right) 

def height(root):
    if root:
        return 1+max(height(root.left), height(root.right))
    else:
        return -1
   
# Driver program to test above function


root = Node(5)
root1 = root.val
root.left = Node(3)
root.right = Node(2)
root.left.left = Node(1)
root.left.left.left = Node(6)
root.left.left.right = Node(4)
root.right.right= Node(7)
root.right.right.right= Node(9)

# print("Height of the Binary Tree: ", height(root))
treeHeight = height(root)


# Total nodes required to compelete binary tree
totalNodes = 2**(treeHeight + 1) -1

# print("Required Nodes : ",2**(treeHeight + 1) -1)

ls =[]
# print("Inorder traversal ")
inorder(root)

index = ls.index(root1)

treeLeft =[]
treeRight = []
for i in range(len(ls)):
    if i < index:
        treeLeft.append(ls[i])
    elif i == index:
        pass
    else:
        treeRight.append(ls[i])

print("Nodes at Same Level and horizontal distance between 2 nodes ")
print()
print("---**---**---**---**---**---**---**---**---**---**---**---**---**---")
print()
for i in treeLeft:
    for j in treeRight:
    #     print("Dist(",i,root1,") = ", findDistance(root, i, root1))
    #     print("Dist(",root1,j,") = ", findDistance(root, j, root1))
        
      
        if findDistance(root, i, root1) == findDistance(root, j, root1):
            print("Nodes are : (",i,",",j, ")  &  Horizontal Distance between (",i,",",j,"): ", findDistance(root, i, root1))
print()
print("---**---**---**---**---**---**---**---**---**---**---**---**---**---")
print()
print("count of the position where the node is not present : ", totalNodes - len(ls))
print()
print("---**---**---**---**---**---**---**---**---**---**---**---**---**---")


"""
Program Output : 
Nodes at Same Level and horizontal distance between 2 nodes 

---**---**---**---**---**---**---**---**---**---**---**---**---**---

Nodes are : ( 6 , 9 )  &  Horizontal Distance between ( 6 , 9 ):  3
Nodes are : ( 1 , 7 )  &  Horizontal Distance between ( 1 , 7 ):  2
Nodes are : ( 4 , 9 )  &  Horizontal Distance between ( 4 , 9 ):  3
Nodes are : ( 3 , 2 )  &  Horizontal Distance between ( 3 , 2 ):  1

---**---**---**---**---**---**---**---**---**---**---**---**---**---

count of the position where the node is not present :  7

---**---**---**---**---**---**---**---**---**---**---**---**---**---
"""