题目:在树中加一行
代码:
```
packageTree;
/**
* Created by gmy on 2017/6/19.
*/
public classTreeNode {
intval;
TreeNodeleft;
TreeNoderight;
TreeNode(intx) {
this.val=x;
}
}
packageTree;
/**
* Created by gmy on 2017/6/19.
*/
public classSolution {
publicTreeNode addOneRow(TreeNode t,intv,intd){
if(d==1){
TreeNode n=newTreeNode(v);
System.out.println(n.val);
n.left=t;
returnn;
}
insert(v,t,1,d);
returnt;
}
public voidinsert(intval,TreeNode node,intdepth,intn){
if(node==null)
return;
if(depth==n-1){
TreeNode t=node.left;
node.left=newTreeNode(val);
node.left.left=t;
t=node.right;
node.right=newTreeNode(val);
node.right.right=t;
}
else{
insert(val,node.left,depth+1,n);
insert(val,node.right,depth+1,n);
}
}
}
```
packageTree;
/**
* Created by gmy on 2017/6/19.
*/
public classtest {
public static voidmain(String[] args) {
//创建树
TreeNode treeNode=newTreeNode(4);
TreeNode treeNode1=newTreeNode(2);
TreeNode treeNode2=newTreeNode(6);
TreeNode treeNode3=newTreeNode(3);
TreeNode treeNode4=newTreeNode(1);
TreeNode treeNode5=newTreeNode(5);
treeNode.left=treeNode1;
treeNode.right=treeNode2;
treeNode1.left=treeNode3;
treeNode1.right=treeNode4;
treeNode2.left=treeNode5;
Solution s=newSolution();
pre( s.addOneRow(treeNode,1,2));
}
public static voidpre(TreeNode treeNode){//先序遍历
if(treeNode!=null){
System.out.print(treeNode.val+" ");
pre(treeNode.left);
pre(treeNode.right);
}
}
}