Given the root of a binary tree, then valuevand depthd, you need to add a row of nodes with valuevat the given depthd. The root node is at depth 1.

The adding rule is: given a positive integer depthd, for each NOT null tree nodesNin depthd-1, create two tree nodes with valuevasN'sleft subtree root and right subtree root. AndN'soriginal left subtreeshould be the left subtree of the new left subtree root, itsoriginal right subtreeshould be the right subtree of the new right subtree root. If depthdis 1 that means there is no depth d-1 at all, then create a tree node with valuevas 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.

Solution: DFS,直到当前层数为depth - 1时,加nodes

    public TreeNode addOneRow(TreeNode root, int v, int d) {
        if (d == 1) {
            TreeNode newRoot = new TreeNode(v);
            newRoot.left = root;
            return newRoot;
        }
        helper(root, v, 1, d);
        return root;
    }
    private void helper(TreeNode root, int v, int d, int depth) {
        if (root == null) {
            return;
        }
        if (d < depth - 1) {
            helper(root.left, v, d + 1, depth);
            helper(root.right, v, d + 1, depth);
        }
        if (d == depth - 1) {
            TreeNode left = new TreeNode(v);
            TreeNode right = new TreeNode(v);
            left.left = root.left;
            right.right = root.right;
            root.left = left;
            root.right = right;
        }

    }

更多方法:https://discuss.leetcode.com/topic/92964/java-three-methods-one-bfs-and-two-dfs

results matching ""

    No results matching ""