Straightforward AC Java DFS Solution with Explanation


  • 0
    public class Solution {
        public TreeNode addOneRow(TreeNode root, int v, int d) {
            return helper(root,d,1,v,true);
        }
        //t is current node,d is target depth, c is current depth l means whether its on left or right
        public TreeNode helper(TreeNode t,int d,int c,int v,boolean l){
            if(d!=c&&t==null) return null; //if current depth is not the target depth and current node is null, then return
            if(d==c){
            TreeNode node = new TreeNode(v);
                if(l){
                    // if currrent node is on the left, make it left subtree of inserted node 
                    node.left = t;
                }else{
                    //if current node is on right, make current node right subtree of inserted node
                    node.right = t;
                }
                return node;
            }
            // if current depth does not reach the target depth , continue to do dfs
            t.left = helper(t.left,d,c+1,v,true);
            t.right = helper(t.right,d,c+1,v,false);
            return t;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.