623. Add One Row to Tree
阿新 • • 發佈:2017-12-11
如果 left 搜索 size 二叉 一行 == dep post original left subtree should be the left subtree of the new left subtree root, its original right subtree should be the right subtree of the new right subtree root. If depth
Given the root of a binary tree, then value v
and depth d
, you need to add a row of nodes with value v
at the given depth d
. The root node is at depth 1.
The adding rule is: given a positive integer depth d
, for each NOT null tree nodes N
in depth d-1
, create two tree nodes with value v
as N‘s
left subtree root and right subtree root. And N‘s
d
is 1 that means there is no depth d-1 at all, then create a tree node with value v as the new root of the whole original tree, and the original tree is the new root‘s left subtree.Example 1:
Input: A binary tree as following: 4 / 2 6 / \ / 3 1 5 v = 1 d = 2 Output: 4 / 1 1 / 2 6 / \ / 3 1 5
給二叉樹添加一行。
因為是給某一行整體添加,所以直接想到的是類似廣度優先搜索算法那樣,開一個queue,保存每一行節點的信息,然後開一個變量記錄這是第幾行。如果這一行正好是需要替換的上一行,那直接給在這些已保存的節點和子節點之間插入一行即可。
1 class Solution { 2 public: 3 TreeNode* addOneRow(TreeNode* root, int v, int d) { 4 if (d==1) { 5 TreeNode* t = new TreeNode(v); 6 t->left = root; 7 return t; 8 } 9 int l = 1; 10 queue<TreeNode*> q; 11 q.push(root); 12 while (l<d-1) { 13 int len = q.size(); 14 for (int i=0; i<len; ++i) { 15 if(q.front()->left) 16 q.push(q.front()->left); 17 if(q.front()->right) 18 q.push(q.front()->right); 19 q.pop(); 20 } 21 ++l; 22 } 23 int len = q.size(); 24 for (int i=0; i<len; ++i) { 25 TreeNode* t = q.front()->left; 26 q.front()->left = new TreeNode(v); 27 q.front()->left->left = t; 28 29 t = q.front()->right; 30 q.front()->right = new TreeNode(v); 31 q.front()->right->right = t; 32 33 q.pop(); 34 } 35 return root; 36 } 37 };
623. Add One Row to Tree