【Add One Row to Tree】Leetcode解题 leetcode-623

Add One Row to Tree (623)

在原本的二元树的某一层插入新节点(后面一样是旧节点)

bfs遍历树(直到到要补的层前),插入左值与右值(可能为null)

注意题目要替换的层树可以是第一层(有指定是左边续接root)

code (java)

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode() {} *     TreeNode(int val) { this.val = val; } *     TreeNode(int val, TreeNode left, TreeNode right) { *         this.val = val; *         this.left = left; *         this.right = right; *     } * } */class Solution {    TreeNode add(TreeNode root ,int val, int depth,int d){        // 如果有一边是null        if(root==null )return null;        if(depth==d+1){            TreeNode t1 = root.right,t2 = root.left;                        // add new val            root.right = new TreeNode(val);            root.left = new TreeNode(val);                        // add odd point            root.right.right = t1;            root.left.left = t2;            return root;        }        else{           root.left = add(root.left,val,depth,d+1);           root.right = add(root.right,val,depth,d+1);         }        return root;    }    public TreeNode addOneRow(TreeNode root, int val, int depth) {        if(root==null)return null;        if(depth==1){            TreeNode a = root;            root = new TreeNode(val);            root.left = a;            return root;        }        return add(root,val,depth,1);            }}

关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章