谁能帮我改写LeetCode 919. 完全二叉树插入器的代码成长尾?
- 内容介绍
- 文章标签
- 相关推荐
本文共计603个文字,预计阅读时间需要3分钟。
设计一个CBTInserter,使用指定完全二叉树初始化。
三个功能:- `insert(val)`:向二叉树中插入一个新值,并返回插入后二叉树的根节点。- `get_root()`:获取二叉树的根节点。
leetcode.com/problems/complete-binary-tree-inserter/设计一个CBTInserter,使用给定完全二叉树初始化。三个功能;
- CBTInserter(TreeNode root) initializes the data structure on a given tree with head node root;
- CBTInserter.insert(int v) will insert a TreeNode into the tree with value node.val = v so that the tree remains complete, and returns the value of the parent of the inserted TreeNode;
- CBTInserter.get_root() will return the head node of the tree.
主要涉及完全二叉树的插入。
解法一:dfs based
对给定的完全二叉树,先计算其最大高度maxlayer,以及深度最深的节点数numoflastlayer。如果numoflastlayer<2^(maxlayer-1),说明应该在maxlayer-1层第一个子节点数小于2的节点插入;如果numoflastlayer==2^(maxlayer-1),说明应该在maxlayer层第一个子节点处插入,利用dfs可以完成。
本文共计603个文字,预计阅读时间需要3分钟。
设计一个CBTInserter,使用指定完全二叉树初始化。
三个功能:- `insert(val)`:向二叉树中插入一个新值,并返回插入后二叉树的根节点。- `get_root()`:获取二叉树的根节点。
leetcode.com/problems/complete-binary-tree-inserter/设计一个CBTInserter,使用给定完全二叉树初始化。三个功能;
- CBTInserter(TreeNode root) initializes the data structure on a given tree with head node root;
- CBTInserter.insert(int v) will insert a TreeNode into the tree with value node.val = v so that the tree remains complete, and returns the value of the parent of the inserted TreeNode;
- CBTInserter.get_root() will return the head node of the tree.
主要涉及完全二叉树的插入。
解法一:dfs based
对给定的完全二叉树,先计算其最大高度maxlayer,以及深度最深的节点数numoflastlayer。如果numoflastlayer<2^(maxlayer-1),说明应该在maxlayer-1层第一个子节点数小于2的节点插入;如果numoflastlayer==2^(maxlayer-1),说明应该在maxlayer层第一个子节点处插入,利用dfs可以完成。

