[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

猜你喜欢

转载自blog.csdn.net/Peng_maple/article/details/82620262