打印距离叶子节点为k的节点 Print nodes that are at distance k from a leaf node

本文介绍了一个算法,用于在给定的二叉树中查找距离任意叶节点k个位置的所有节点。该算法的时间复杂度为O(n),其中n为二叉树中的节点数量。通过遍历树并跟踪祖先节点,当遇到叶节点时,算法会打印出距离叶节点k个位置的祖先节点,并使用布尔数组记录已打印的节点。

Print all nodes that are at distance k from a leaf node

Given a Binary Tree and a positive integer k, print all nodes that are distance k from a leaf node.

Here the meaning of distance is different from previous post. Here k distance from a leaf means k levels higher than a leaf node. For example if k is more than height of Binary Tree, then nothing should be printed. Expected time complexity is O(n) where n is the number nodes in the given Binary Tree.

The idea is to traverse the tree. Keep storing all ancestors till we hit a leaf node. When we reach a leaf node, we print the ancestor at distance k. We also need to keep track of nodes that are already printed as output. For that we use a boolean array visited[].

/* Program to print all nodes which are at distance k from a leaf */
#include <iostream>
using namespace std;
#define MAX_HEIGHT 10000
 
struct Node
{
    int key;
    Node *left, *right;
};
 
/* utility that allocates a new Node with the given key  */
Node* newNode(int key)
{
    Node* node = new Node;
    node->key = key;
    node->left = node->right = NULL;
    return (node);
}
 
/* This function prints all nodes that are distance k from a leaf node
   path[] --> Store ancestors of a node
   visited[] --> Stores true if a node is printed as output.  A node may be k
                 distance away from many leaves, we want to print it once */
void kDistantFromLeafUtil(Node* node, int path[], bool visited[],
                          int pathLen, int k)
{
    // Base case
    if (node==NULL) return;
 
    /* append this Node to the path array */
    path[pathLen] = node->key;
    visited[pathLen] = false;
    pathLen++;
 
    /* it's a leaf, so print the ancestor at distance k only
       if the ancestor is not already printed  */
    if (node->left == NULL && node->right == NULL &&
        pathLen-k-1 >= 0 && visited[pathLen-k-1] == false)
    {
        cout << path[pathLen-k-1] << " ";
        visited[pathLen-k-1] = true;
        return;
    }
 
    /* If not leaf node, recur for left and right subtrees */
    kDistantFromLeafUtil(node->left, path, visited, pathLen, k);
    kDistantFromLeafUtil(node->right, path, visited, pathLen, k);
}
 
/* Given a binary tree and a nuber k, print all nodes that are k
   distant from a leaf*/
void printKDistantfromLeaf(Node* node, int k)
{
    int path[MAX_HEIGHT];
    bool visited[MAX_HEIGHT] = {false};
    kDistantFromLeafUtil(node, path, visited, 0, k);
}
 
/* Driver program to test above functions*/
int main()
{
    // Let us create binary tree given in the above example
    Node * root = newNode(1);
    root->left = newNode(2);
    root->right = newNode(3);
    root->left->left = newNode(4);
    root->left->right = newNode(5);
    root->right->left = newNode(6);
    root->right->right = newNode(7);
    root->right->left->right = newNode(8);
 
    cout << "Nodes at distance 2 are: ";
    printKDistantfromLeaf(root, 2);
 
    return 0;
}


base_id,compare_id1,compare_id2,distance,change_num,param C2215-G3-GAA-R30,C2215-G3-GAA-R30,C2215-G3-GAA-R34,2.4705882352941178,3,"['SL#BRFDelayPhase', 'SL1#BRFDelayPhase', 'SL2#BRFDelayPhase']" 分组还是按baseid分,但是每行打的标签是df的compare_id1 和df的compare_id2的组合即(compare_id1 , compare_id2) def draw_trees_from_df__(df, root_name="ROOT", group_size=1, save_dir="output", file_format="png"): """ 从 DataFrame 中读取数据,为每个 base_id 生成一个树状图,并保存为文件。 参数: - df: 包含数据的 DataFrame,必须包含 "base_id" 和 "param" 列。 - root_name: 根节点名称。 - group_size: 每组处理的 base_id 数量(默认为 1)。 - save_dir: 图片保存的目录。 - file_format: 图片保存格式,如 png, svg, pdf 等。 """ # 创建保存目录(如果不存在) os.makedirs(save_dir, exist_ok=True) # 获取所有 base_id base_ids = df["base_id"].unique().tolist() # 分组 groups = [base_ids[i:i + group_size] for i in range(0, len(base_ids), group_size)] for group_idx, group in enumerate(groups): # 每个 group 单独新建一个 figure plt.figure(figsize=(8, 6)) ax = plt.subplot(111) combined_G = nx.DiGraph() all_baseid_labels = defaultdict(list) node_colors = {} color_map = { group[0]: "lightblue", group[1] if len(group) > 1 else None: "lightgreen", group[2] if len(group) > 2 else None: "salmon" } # 为每个 base_id 构建子图并合并 for base_id in group: group_df = df[df["base_id"] == base_id] for idx, row in group_df.iterrows(): path = row["param"] full_path = [root_name] + path current_node = root_name if not combined_G.has_node(current_node): combined_G.add_node(current_node) node_colors[current_node] = "white" # 根节点颜色不变 for param in path: next_node = param if not combined_G.has_node(next_node): combined_G.add_node(next_node) node_colors[next_node] = color_map[base_id] combined_G.add_edge(current_node, next_node) current_node = next_node # 记录该终点节点对应的 base_id all_baseid_labels[current_node].append(base_id) # 分层布局 layers = {} visited = set() queue = [(root_name, 0)] while queue: node, depth = queue.pop(0) if node in visited: continue visited.add(node) layers[node] = depth for neighbor in combined_G.successors(node): if neighbor not in layers: layers[neighbor] = depth + 1 queue.append((neighbor, depth + 1)) for node in combined_G.nodes: combined_G.nodes[node]["layer"] = layers.get(node, 0) pos = nx.multipartite_layout(combined_G, subset_key="layer", align="horizontal") # 构建标签映射:节点名 -> 显示名(你想要的特征名) labels = {node: node for node in combined_G.nodes} # 绘图 node_color_list = [node_colors.get(node, "lightgray") for node in combined_G.nodes] nx.draw( combined_G, pos, ax=ax, with_labels=True, labels=labels, node_size=400, node_color=node_color_list, font_size=10, arrows=True, edge_color="gray" ) # 添加 base_id 标注在节点旁边 for node, base_ids in all_baseid_labels.items(): x, y = pos[node] ax.text( x, y + 0.05, "\n".join(base_ids), fontsize=8, color="red", ha='center', va='bottom' ) title = f"Group: {', '.join(group)}" ax.set_title(title) plt.tight_layout() # 保存图像,使用 group 中的 base_id 作为文件名 filename = "_".join(group) save_path = os.path.join(save_dir, f"{filename}.{file_format}") plt.savefig(save_path, format=file_format, dpi=200, bbox_inches='tight') plt.close() # 关闭当前图像,避免占用内存 print(f"Saved: {save_path}")
最新发布
09-05
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值