[英]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
让我很清楚,我没有得到水平距离是什么。
但从我的角度来看。 水平距离是指:同一级别的给定节点之间缺少或存在的节点。
在我的情况下,当我试图找出早上7
点和1
点之间的距离时,得到 output 即 2。这就是为什么我想上面提到的方式。
但是,如果我尝试找出上午9
点和6
点之间的距离,则将 output 设为 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;
}
}
一个例子的解释将不胜感激。 并很高兴进一步解释
你知道定义:
5
/ \
4 6
在这里,计算h(4,6)
h(4,6) = 0
5
/ \
4 6
\
2
在这里,要计算h(2,6)
, 2
是 4 的右孩子(**显然,如果 node 是唯一的孩子,它必须被视为右孩子):
所以h(2,4)=+1
召回h(4,6)=0
所以h(2,6) = 1
关于你的一个例子,比如h(9,6)
h(9,7) = 2
h(2,3) = 0
h(3,1) = 1 (1 only child so +1)
h(1,6) = 1 (same)
total: 4
** 我想选择 +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
---**---**---**---**---**---**---**---**---**---**---**---**---**---
"""
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.