LeetCode #623 Add One Row to Tree 在二叉樹中增加一行

623 Add One Row to Tree 在二叉樹中增加一行

Description:
Given the root of a binary tree and two integers val and depth, add a row of nodes with value val at the given depth depth.

Note that the root node is at depth 1.

The adding rule is:

Given the integer depth, for each not null tree node cur at the depth depth - 1, create two tree nodes with value val as cur's left subtree root and right subtree root.
cur's original left subtree should be the left subtree of the new left subtree root.
cur's original right subtree should be the right subtree of the new right subtree root.
If depth == 1 that means there is no depth depth - 1 at all, then create a tree node with value val as the new root of the whole original tree, and the original tree is the new root's left subtree.

Example:

Example 1:

addrow-tree 1

Input: root = [4,2,6,3,1,5], val = 1, depth = 2
Output: [4,1,1,2,null,null,6,3,1,5]

Example 2:

addrow-tree 2

Input: root = [4,2,null,3,1], val = 1, depth = 3
Output: [4,2,null,1,1,3,null,null,1]

Constraints:

The number of nodes in the tree is in the range [1, 10^4].
The depth of the tree is in the range [1, 10^4].
-100 <= Node.val <= 100
-10^5 <= val <= 10^5
1 <= depth <= the depth of tree + 1

題目描述:
給定一個二叉樹,根節(jié)點為第1層,深度為 1。在其第 d 層追加一行值為 v 的節(jié)點跟磨。

添加規(guī)則:給定一個深度值 d (正整數(shù))间聊,針對深度為 d-1 層的每一非空節(jié)點 N吱晒,為 N 創(chuàng)建兩個值為 v 的左子樹和右子樹。

將 N 原先的左子樹沦童,連接為新節(jié)點 v 的左子樹仑濒;將 N 原先的右子樹,連接為新節(jié)點 v 的右子樹偷遗。

如果 d 的值為 1墩瞳,深度 d - 1 不存在,則創(chuàng)建一個新的根節(jié)點 v氏豌,原先的整棵樹將作為 v 的左子樹喉酌。

示例 :

示例 1:

輸入:
二叉樹如下所示:

       4
     /   \
    2     6
   / \   / 
  3   1 5   

v = 1

d = 2

輸出:

       4
      / \
     1   1
    /     \
   2       6
  / \     / 
 3   1   5   

示例 2:

輸入:
二叉樹如下所示:

      4
     /   
    2    
   / \   
  3   1    

v = 1

d = 3

輸出:

      4
     /   
    2
   / \    
  1   1
 /     \  
3       1

注意:

輸入的深度值 d 的范圍是:[1,二叉樹最大深度 + 1]泵喘。
輸入的二叉樹至少有一個節(jié)點泪电。

思路:

  1. 遞歸
    分為左子樹和右子樹遞歸
  2. BFS
    按照層序遍歷到 depth 深度之后給隊列中的每一個節(jié)點加上 val 的節(jié)點
    時間復(fù)雜度 O(n), 空間復(fù)雜度 O(n)

代碼:
C++:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution 
{
public:
    TreeNode* addOneRow(TreeNode* root, int val, int depth) 
    {
        if (depth == 1) return new TreeNode(val, root, nullptr);
        queue<TreeNode*> q{{root}};
        while (--depth > 1)
        {
            int s = q.size();
            while (s--)
            {
                auto cur = q.front();
                q.pop();
                if (cur -> left) q.emplace(cur -> left);
                if (cur -> right) q.emplace(cur -> right);
            }
        }
        while (!q.empty())
        {
            auto item = q.front();
            item -> left = new TreeNode(val, item -> left, nullptr);
            item -> right = new TreeNode(val, nullptr, item -> right);
            q.pop();
        }
        return root;
    }
};

Java:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public TreeNode addOneRow(TreeNode root, int v, int d) {
        if (d == 0 || d == 1) {
            TreeNode t = new TreeNode(v);
            if (d == 1) t.left = root;
            else t.right = root;
            return t;
        }
        if (root != null && d > 1) {
            root.left = addOneRow(root.left, v, d > 2 ? d - 1 : 1);
            root.right = addOneRow(root.right, v, d > 2 ? d - 1 : 0);
        }
        return root;
    }
}

Python:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def addOneRow(self, root: TreeNode, val: int, depth: int) -> TreeNode:
        if depth == 1:
            return TreeNode(val, root, None)
        queue = [root]
        while (depth := depth - 1) > 1:
            s = len(queue) + 1
            while (s := s - 1):
                cur = queue.pop(0)
                (cur.left and queue.append(cur.left)) or (cur.right and queue.append(cur.right))
        for item in queue:
            item.left, item.right = TreeNode(val, left=item.left), TreeNode(val, right=item.right)
        return root
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市纪铺,隨后出現(xiàn)的幾起案子相速,更是在濱河造成了極大的恐慌,老刑警劉巖鲜锚,帶你破解...
    沈念sama閱讀 218,858評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件突诬,死亡現(xiàn)場離奇詭異,居然都是意外死亡芜繁,警方通過查閱死者的電腦和手機旺隙,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,372評論 3 395
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來骏令,“玉大人蔬捷,你說我怎么就攤上這事±拼” “怎么了抠刺?”我有些...
    開封第一講書人閱讀 165,282評論 0 356
  • 文/不壞的土叔 我叫張陵塔淤,是天一觀的道長。 經(jīng)常有香客問我速妖,道長高蜂,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,842評論 1 295
  • 正文 為了忘掉前任罕容,我火速辦了婚禮备恤,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘锦秒。我一直安慰自己露泊,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,857評論 6 392
  • 文/花漫 我一把揭開白布旅择。 她就那樣靜靜地躺著惭笑,像睡著了一般。 火紅的嫁衣襯著肌膚如雪生真。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,679評論 1 305
  • 那天川蒙,我揣著相機與錄音,去河邊找鬼畜眨。 笑死术瓮,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的早抠。 我是一名探鬼主播撬讽,決...
    沈念sama閱讀 40,406評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼甘苍!你這毒婦竟也來了烘豌?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,311評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎囚聚,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體茁计,經(jīng)...
    沈念sama閱讀 45,767評論 1 315
  • 正文 獨居荒郊野嶺守林人離奇死亡谓松,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,945評論 3 336
  • 正文 我和宋清朗相戀三年鬼譬,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片竣贪。...
    茶點故事閱讀 40,090評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖巩螃,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情颤枪,我是刑警寧澤汗捡,帶...
    沈念sama閱讀 35,785評論 5 346
  • 正文 年R本政府宣布扇住,位于F島的核電站,受9級特大地震影響锄贼,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜宅荤,卻給世界環(huán)境...
    茶點故事閱讀 41,420評論 3 331
  • 文/蒙蒙 一冯键、第九天 我趴在偏房一處隱蔽的房頂上張望庸汗。 院中可真熱鬧,春花似錦、人聲如沸掩蛤。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,988評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽蜈亩。三九已至前翎,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間港华,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,101評論 1 271
  • 我被黑心中介騙來泰國打工冒萄, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留橙数,地道東北人。 一個月前我還...
    沈念sama閱讀 48,298評論 3 372
  • 正文 我出身青樓崖技,卻偏偏與公主長得像迎献,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子吁恍,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,033評論 2 355

推薦閱讀更多精彩內(nèi)容