C++ 中二叉樹對角線遍歷的第 k 個節點
本教程中,我們將編寫一個查詢二叉樹對角線遍歷中第 k 個節點的程式。
讓我們看看解決這個問題的步驟。
- 使用一些樣例資料初始化二叉樹。
- 初始化數字 k。
- 使用資料結構佇列對角遍歷二叉樹。
- 在每個節點上遞減 k 的值。
- 當 k 變為 0 時返回節點。
- 如果沒有這樣的節點,則返回 -1。
示例
讓我們看看程式碼。
#include <bits/stdc++.h> using namespace std; struct Node { int data; Node *left, *right; }; Node* getNewNode(int data) { Node* node = (Node*)malloc(sizeof(Node)); node->data = data; node->left = node->right = NULL; return node; } int findDiagonalKthElement(Node* root, int k) { if (root == NULL || k == 0) { return -1; } int result = -1; queue<Node*> q; q.push(root); q.push(NULL); while (!q.empty()) { Node* temp = q.front(); q.pop(); if (temp == NULL) { if (q.empty()) { if (k == 0) { return result; }else { break; } } q.push(NULL); }else { while (temp) { if (k == 0) { return result; } k--; result = temp->data; if (temp->left) { q.push(temp->left); } temp = temp->right; } } } return -1; } int main() { Node* root = getNewNode(10); root->left = getNewNode(5); root->right = getNewNode(56); root->left->left = getNewNode(3); root->left->right = getNewNode(22); root->right->right = getNewNode(34); root->right->right->left = getNewNode(45); root->left->right->left = getNewNode(67); root->left->right->right = getNewNode(100); int k = 9; cout << findDiagonalKthElement(root, k) << endl; return 0; }
輸出
如果您執行以上程式碼,則會得到以下結果。
67
結論
如果您在教程中有任何疑問,請在評論部分提及。
廣告