用 C++ 语言在二叉树垂直顺序遍历中查找第 k 个节点
假设我们有一棵二叉树和一个值 K。任务是在垂直顺序遍历中打印第 K 个节点。如果不存在该节点,则返回 -1。因此,如果树如下所示:-
垂直顺序遍历如下:-
4 2 1 5 6 3 8 7 9
因此,如果 K = 3,则结果将为 1。
方法很简单。我们将执行垂直顺序遍历,然后检查当前节点是否是第 k 个节点,如果是,则返回。
示例
#include<iostream> #include<map> #include<vector> #include<queue> using namespace std; class Node { public: int key; Node *left, *right; }; Node* getNode(int key){ Node* node = new Node; node->key = key; node->left = node->right = NULL; return node; } int findKthNodeVertical(Node* root, int k) { if (!root || k == 0) return -1; int n = 0; int k_node = -1; map<int, vector<int> > current_map; int hd = 0; queue<pair<Node*, int> > que; que.push(make_pair(root, hd)); while (!que.empty()) { pair<Node*, int> temp = que.front(); que.pop(); hd = temp.second; Node* node = temp.first; current_map[hd].push_back(node->key); if (node->left != NULL) que.push(make_pair(node->left, hd - 1)); if (node->right != NULL) que.push(make_pair(node->right, hd + 1)); } map<int, vector<int> >::iterator it; for (it = current_map.begin(); it != current_map.end(); it++) { for (int i = 0; i < it->second.size(); ++i) { n++; if (n == k) return (it->second[i]); } } if (k_node == -1) return -1; } int main() { Node* root = getNode(1); root->left = getNode(2); root->right = getNode(3); root->left->left = getNode(4); root->left->right = getNode(5); root->right->left = getNode(6); root->right->right = getNode(7); root->right->left->right = getNode(8); root->right->right->right = getNode(9); int k = 3; cout << "Kth node in vertical traversal: " << findKthNodeVertical(root, k); }
输出
Kth node in vertical traversal: 1
广告