C++ 最大二叉樹 II
假設我們有一個最大二叉樹的根節點:最大二叉樹是一棵樹,其中每個節點的值都大於其子樹中的任何其他值。假設我們有一個名為 construct() 的方法。它可以從列表 A 構造一個根節點。construct() 方法如下:
如果列表 A 為空,則返回 null。
否則,令 A[i] 為列表 A 中的最大元素。然後建立一個值為 A[i] 的根節點。
根節點的左子節點將是 construct([A[0], A[1], ..., A[i-1]])
根節點的右子節點將是 construct([A[i+1], A[i+2], ..., A[n - 1]]) [n 是 A 的長度]
返回根節點。
請注意,我們沒有直接得到 A,只有根節點 root = construct(A)。現在假設 B 是 A 的副本,其中添加了值 val。保證 B 的值唯一。我們必須構造(B)。如果值為 5,輸入樹如下:

輸出樹如下:

為了解決這個問題,我們將遵循以下步驟:
定義一個遞迴方法 solve()。它接收 root 和 val 作為引數。
如果樹為空,則建立一個值為 val 的新節點,並返回該節點。
如果 root 的值 < val,則
temp := 建立一個值為 val 的新節點
temp 的左子節點 := root
返回 temp
root 的右子節點 := solve(root 的右子節點, val)
返回 root
讓我們看看下面的實現來更好地理解:
示例
#include <bits/stdc++.h>
using namespace std;
class TreeNode{
public:
int val;
TreeNode *left, *right;
TreeNode(int data){
val = data;
left = NULL;
right = NULL;
}
};
void insert(TreeNode **root, int val){
queue<TreeNode*> q;
q.push(*root);
while(q.size()){
TreeNode *temp = q.front();
q.pop();
if(!temp->left){
if(val != NULL)
temp->left = new TreeNode(val);
else
temp->left = new TreeNode(0);
return;
}else{
q.push(temp->left);
}
if(!temp->right){
if(val != NULL)
temp->right = new TreeNode(val);
else
temp->right = new TreeNode(0);
return;
}else{
q.push(temp->right);
}
}
}
TreeNode *make_tree(vector<int> v){
TreeNode *root = new TreeNode(v[0]);
for(int i = 1; i<v.size(); i++){
insert(&root, v[i]);
}
return root;
}
void tree_level_trav(TreeNode*root){
if (root == NULL) return;
cout << "[";
queue<TreeNode *> q;
TreeNode *curr;
q.push(root);
q.push(NULL);
while (q.size() > 1) {
curr = q.front();
q.pop();
if (curr == NULL){
q.push(NULL);
}
else {
if(curr->left)
q.push(curr->left);
if(curr->right)
q.push(curr->right);
if(curr == NULL || curr->val == 0){
cout << "null" << ", ";
}else{
cout << curr->val << ", ";
}
}
}
cout << "]"<<endl;
}
class Solution {
public:
TreeNode* insertIntoMaxTree(TreeNode* root, int val) {
if(!root)return new TreeNode(val);
if(root->val < val){
TreeNode* temp = new TreeNode(val);
temp->left = root;
return temp;
}
root->right = insertIntoMaxTree(root->right, val);
return root;
}
};
main(){
vector<int> v = {4,1,3,NULL,NULL,2};
TreeNode *root = make_tree(v);
Solution ob;
tree_level_trav(ob.insertIntoMaxTree(root, 5));
}輸入
[4,1,3,null,null,2] 5
輸出
[5, 4, 1, 3, null, null, 2, ]
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP