leetcode题解-998-最大二叉树Ⅱ

题目

没能理解题意。。。

我感觉是给了一个已经构造好的最大二叉树,然后新插入一个值为val的结点进来。

这个解答告诉了这个题是要做啥。然后发现是对比三幅例子的树图可以得到插入val结点进来的要求。

分成如下2种情况:

  1. 大于root,则把 root作为val节点的左子树;
  2. 小于root,则把 val节点作为root的右子树;

secretname way

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* insertIntoMaxTree(TreeNode* root, int val)
{
if (!root || root->val < val)
{
TreeNode* node = new TreeNode(val);
node->left = root;
return node;
}

root->right = insertIntoMaxTree(root->right, val);
return root;
}
};

References

https://leetcode-cn.com/problems/maximum-binary-tree-ii/solution/go-0ms-wu-di-gui-by-yuhhen/

https://leetcode-cn.com/problems/maximum-binary-tree-ii/solution/c-di-gui-jian-ji-dai-ma-by-secretname/