Simple dfs Java solution

  • 0
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
    public class Solution {
        public TreeNode addOneRow(TreeNode root, int v, int d) {
            return dfs(root,v,d, true);
        private TreeNode dfs(TreeNode root, int v, int d, boolean dir){
                TreeNode newRoot=new TreeNode(v);
                if(dir) newRoot.left=root;
                else newRoot.right=root;
                return newRoot;
            if(root==null) return root;
            root.left=dfs(root.left, v, d-1,true);
            root.right=dfs(root.right, v, d-1,false);
            return root;

Log in to reply

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