1. 程式人生 > >[LeetCode] 623. Add One Row to Tree

[LeetCode] 623. Add One Row to Tree

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:


這裡寫圖片描述

解析

在第d層增加一層全為v的結點,並且d-1層的左節點為新增層的左節點,右節點為新增層的右節點。

解法1:迭代queue

使用queue進行層次遍歷,對於每一層,如果當前層的高度等於d-1,則先獲取當前層的子節點,然後增加一層,再把子節點鏈上,直接結束迴圈。

class Solution {
public:
    TreeNode* addOneRow(TreeNode* root, int v, int d) {
        TreeNode * node = new TreeNode(v);
        if(d==1){
            node->left = root;
            return
node; } queue<TreeNode*> q; q.push(root); int hight = 1; while(!q.empty() || hight < d){ int size = q.size(); for(int i=0;i<size;i++){ TreeNode* p = q.front(); q.pop(); if(hight == d-1
){ TreeNode* leftnode = new TreeNode(v); TreeNode* rightnode = new TreeNode(v); leftnode->left = p->left; rightnode->right = p->right; p->left = leftnode; p->right = rightnode; } else{ if(p->left) q.push(p->left); if(p->right) q.push(p->right); } } hight ++; } return root; } };

解法2:遞迴

利用d的值作為flag:
當d=1時,將root連線到新節點的左節點上;
當d=0時,將root連線到新節點的右節點上。然後返回新建的節點。
當root不為空並且d > 1時,對root的左節點呼叫遞迴函式,若d = 2,直接進行賦值為1,對root的右節點呼叫遞迴函式,若d=2,直接賦值為0。

class Solution {
public:
    TreeNode* addOneRow(TreeNode* root, int v, int d) {
        if(d == 0 || d == 1){
            TreeNode* newNode = new TreeNode(v);
            (d ? newNode->left : newNode->right) = root;
            return newNode;
        }
        if(root && d > 1){
            root->left = addOneRow(root->left, v, d>2 ? d-1:1);
            root->right = addOneRow(root->right, v, d>2 ? d-1:0);
        }
        return root;
    }
};

參考

http://www.cnblogs.com/grandyang/p/7070182.html