From f5ec9f4f602af3667284c38fcfb5ddca53f9a183 Mon Sep 17 00:00:00 2001 From: Yashika Gupta Date: Wed, 5 Oct 2022 16:10:59 +0530 Subject: [PATCH] Create add-one-row-to-tree-at-given-depth --- .../Trees/add-one-row-to-tree-at-given-depth | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 algorithms/CPlusPlus/Trees/add-one-row-to-tree-at-given-depth diff --git a/algorithms/CPlusPlus/Trees/add-one-row-to-tree-at-given-depth b/algorithms/CPlusPlus/Trees/add-one-row-to-tree-at-given-depth new file mode 100644 index 00000000..7ec97f55 --- /dev/null +++ b/algorithms/CPlusPlus/Trees/add-one-row-to-tree-at-given-depth @@ -0,0 +1,28 @@ +PROBLEM---- +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. + +Input: root = [4,2,6,3,1,5], val = 1, depth = 2 +Output: [4,1,1,2,null,null,6,3,1,5] + +ALGORITHM---- + +The idea is to: +In addition to use 1 to indicate attach to left node as required, we can also use 0 to indicate attach to right node; +Compact C++ + +class Solution { +public: + TreeNode* addOneRow(TreeNode* root, int v, int d) { + if (d == 0 || d == 1) { + TreeNode* newroot = new TreeNode(v); + (d ? newroot->left : newroot->right) = root; + return newroot; + } + if (root && d >= 2) { + root->left = addOneRow(root->left, v, d > 2 ? d - 1 : 1); + root->right = addOneRow(root->right, v, d > 2 ? d - 1 : 0); + } + return root; + } +};