623. Add One Row to Tree

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 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 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 };

 

posted @ 2017-12-11 16:27  Zzz...y  阅读(138)  评论(0编辑  收藏  举报