链接:https://leetcode.cn/problems/add-one-row-to-tree/solution/shen-du-you-xian-by-xun-ge-v-4h6w/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
题目
示例
思路
解题思路
对于树的相关问题,递归基本上都可以解决,递归能解决的问题,迭代基本上也行,对于本题就有两种方法一种递归,一种迭代
- 深度优先搜索+递归
我们按照树的高度为参照,递归整个树节点,当高度满足条件,插入新节点
- 广度优先搜索+层次遍历
我们按照树的层次遍历,枚举整个树,当枚举到对应高度层时,对所有节点插入新的节点
代码
深度优先搜索+递归
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
struct TreeNode* addOneRow(struct TreeNode* root, int val, int depth) {
if (root == NULL) {
return NULL;
}
struct TreeNode *node = (struct TreeNode *)malloc(sizeof(struct TreeNode));
if (depth == 1) {//递归到对应高度了,高度为1说明到了叶子结点,只有加一个
node = (struct TreeNode *)malloc(sizeof(struct TreeNode));
node->val = val;
node->left = root;
node->right = NULL;//添加新节点
return node;
}
if (depth == 2) {//递归到对应高度了,加节点
node = (struct TreeNode *)malloc(sizeof(struct TreeNode));
node->val = val;
node->left = root->left;
node->right = NULL;
root->left = node;
node = (struct TreeNode *)malloc(sizeof(struct TreeNode));
node->val = val;
node->left = NULL;
node->right = root->right;
root->right = node;//添加新节点,左右都得加
} else {
root->left = addOneRow(root->left, val, depth - 1);//左右节点都递归遍历
root->right = addOneRow(root->right, val, depth - 1);
}
return root;
}
作者:xun-ge-v
链接:https://leetcode.cn/problems/add-one-row-to-tree/solution/shen-du-you-xian-by-xun-ge-v-4h6w/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
广度优先搜索+层次遍历
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
#define MAX_NODE_SIZE 10000
struct TreeNode* addOneRow(struct TreeNode* root, int val, int depth) {
struct TreeNode* node = NULL;
if (depth == 1) {//高度为1头节点都没有直接返回
node = (struct TreeNode *)malloc(sizeof(struct TreeNode));
node->val = val;
node->left = root;
node->right = NULL;
return node;
}
//以下为树的层次遍历
TreeNode * queue[MAX_NODE_SIZE];
int head = 0, tail = 0;
queue[tail++] = root;
for (int i = 1; i < depth - 1; i++) {
int sz = tail - head;
for (int j = 0; j < sz; j++) {
struct if (queue[head]->left != NULL) {
queue[tail++] = queue[head]->left;
}
if (queue[head]->right != NULL) {
queue[tail++] = queue[head]->right;
}
head++;
}
}
//遍历到了目标层,对队列中所有元素都插入新的节点
for (; head != tail; head++) {
node = (struct TreeNode *)malloc(sizeof(struct TreeNode));
node->val = val;
node->left = queue[head]->left;
node->right = NULL;
queue[head]->left = node;
node = (struct TreeNode *)malloc(sizeof(struct TreeNode));
node->val = val;
node->left = NULL;
node->right = queue[head]->right;
queue[head]->right = node;
}
return root;
}
作者:xun-ge-v
链接:https://leetcode.cn/problems/add-one-row-to-tree/solution/shen-du-you-xian-by-xun-ge-v-4h6w/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。