作者Rushia (みけねこ的鼻屎)
看板Marginalman
標題Re: [閒聊] 每日LeetCode
時間Wed Oct 5 09:25:45 2022
623. Add One Row to Tree
給予一個二元樹,我們要在高度為depth的位置插入一行數值為val的節點。
若depth為1,因為沒有存在深度為0的樹所以令root為新的節點的
左樹。
Example 1:
https://assets.leetcode.com/uploads/2021/03/15/addrow-tree.jpg
Input: root = [4,2,6,3,1,5], val = 1, depth = 2
Output: [4,1,1,2,null,null,6,3,1,5]
思路:
1.對樹進行dfs並用一個boolean紀錄上個節點是對左樹還是右樹訪問
2.當深度為1的時候表示要在這層進行插入,new一個節點並根據上個訪問的節點是
左樹還右樹來決定要把下一層放左還放右
Java Code:
class Solution {
public TreeNode addOneRow(TreeNode root, int val, int depth) {
return addOneRow(root, val, depth, true);
}
public TreeNode addOneRow(TreeNode root, int val, int depth, boolean
isLeft) {
if(depth == 1) {
TreeNode node = new TreeNode(val);
if(isLeft) node.left = root;
else node.right = root;
return node;
}
if(root == null) return null;
root.left = addOneRow(root.left, val, depth - 1, true);
root.right = addOneRow(root.right, val, depth - 1, false);
return root;
}
}
今天也是溫柔善良的樹 好耶
--
https://i.imgur.com/uiFto42.jpg
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 1.160.85.207 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1664933148.A.8C2.html
推 Jaka: 大師 10/05 09:27
推 pandix: 大師 10/05 09:29
推 Ericz7000: 大師 10/05 09:30
推 koy784512: 大師 10/05 09:30
推 abcd991276: 大師 10/05 11:14