Google+ Followers

Saturday, July 22, 2017

[Leetcode] Add One Row to Tree, Solution

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 vas 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   

Example 2:
Input: 
A binary tree as following:
      4
     /   
    2    
   / \   
  3   1    

v = 1

d = 3

Output: 
      4
     /   
    2
   / \    
  1   1
 /     \  
3       1
Note:
  1. The given d is in range [1, maximum depth of the given tree + 1].
  2. The given binary tree has at least one tree node.

[Thoughts]
这个递归就可以解决。遍历树结构,在遍历的过程中检查当前深度是否为指定的深度,如果是,则插入新节点。比较直接、简单。


[Code]

1:    TreeNode* addOneRow(TreeNode* root, int v, int d) {  
2:      if(root == NULL) return root;  
3:        
4:      if(d == 1) {  
5:        TreeNode* newRoot = new TreeNode(v);  
6:        newRoot->left = root;  
7:        return newRoot;  
8:      }  
9:      addOneRowImpl(root, v, 1, d);  
10:      return root;  
11:    }  
12:      
13:    void addOneRowImpl(TreeNode* node, int v, int level, int& d) {  
14:      if(node == NULL) return;  
15:        
16:      if(level == d - 1) {  
17:        TreeNode* left = node->left;  
18:        TreeNode* right = node->right;  
19:        node->left = new TreeNode(v);  
20:        node->left->left = left;  
21:        node->right = new TreeNode(v);  
22:        node->right->right = right;  
23:        return;  
24:      }  
25:        
26:      addOneRowImpl(node->left, v, level+1, d);  
27:      addOneRowImpl(node->right, v, level+1, d);    
28:    }  


Post a Comment