Leetcode_623_在二叉树的中增加一行_数据结构

该说不说的,我觉得写的一气呵成挺完美

class Solution {
    public TreeNode addOneRow(TreeNode root, int val, int depth) {
        if(depth == 1) {
            TreeNode node = new TreeNode(val);
            node.left = root;
            return node;
        }
        dfs(root, 2, depth, val);
        return root;
    }

    void dfs(TreeNode node, int nowDepth, int targetDepth, int val) {
        if(node == null) {
            return;
        }
        if(nowDepth == targetDepth) {
            process(node, val);
        }
        dfs(node.left, nowDepth + 1, targetDepth, val);
        dfs(node.right, nowDepth + 1, targetDepth, val);
    }

    /**
     * 处理cur,为其添加两个值为val的子节点,并把原来的子树挂载在两端
     */
    void process(TreeNode node, int val) {
        TreeNode left = node.left;
        TreeNode right = node.right;
        node.left = new TreeNode(val);
        node.right = new TreeNode(val);
        node.left.left = left;
        node.right.right = right;
    }
}

你可能感兴趣的:(数据结构,daily_algorithm,leetcode,数据结构,深度优先)