我的第三题:
我的是这样的:
朕不知道有什么差别,还在请教原作者,然后还原完整代码是这样的:
想要向系统输入测试用例一样输入[4,2,3,6,null,4,8]什么的,但是用Integar[] 数组来定义,又不对,哭了
226. Invert Binary Tree
还是不习惯写封装的函数,写着写着,怎么就找不到输入输出了呢?这道题本来方法很简单,两个递归调用就解决了,而且还是0ms,可是我想还原完整的函数入口,就重新建树,输出,可是居然不对了,哎呀,怎么搞得,好笨呐/(ㄒoㄒ)/~~
原本的别人的0ms方法是这样的:
public class Solution {
public TreeNode invertTree(TreeNode root) {
if (root == null) {
return null;
}
TreeNode temp = root.left;
root.left = invertTree(root.right);
root.right = invertTree(temp);
return root;
}
}
我的是这样的:
public class Solution {
public TreeNode invertTree(TreeNode root) {
if (root == null) {
return null;
}
TreeNode contain = root.left;//实例变量直接赋值来定义
root.left = root.right;
root.right = contain;
invertTree(root.left);
invertTree(root.right);
return root;
}
}
朕不知道有什么差别,还在请教原作者,然后还原完整代码是这样的:
import java.util.LinkedList;
import java.util.List;
//Definition for a binary tree node.
class TreeNode{
int data;//作为root
TreeNode left;
TreeNode right;
TreeNode(int x){
left = null;
right = null;
data = x;
}
}
public class InvertTree226 {
int [] array = {4,2,7,1,3,6,9};
List<TreeNode> list = new LinkedList<>();//linkedlist没有定义初始大小的构造函数,和arraylist不一样
public void creatBinaryTree(){
for(int index=0; index<array.length; index++){
list.add(new TreeNode(array[index]));//因为数组array是封装类型,要自动拆箱成int型
}
//利用子节点和父节点之间数学关系建树,但是要考虑出界问题
for(int parentIndex=0; parentIndex<array.length/2; parentIndex++){
if(parentIndex *2 + 1>array.length){
break;
}else{
list.get(parentIndex).left = list.get(parentIndex * 2 + 1);
}
if(parentIndex *2 + 2>array.length){
break;
}else{
list.get(parentIndex).right = list.get(parentIndex * 2 + 2);
}
}
}
public TreeNode invertTree(TreeNode root){
if(root==null){
return null;
}//用来做递归出口
TreeNode contain = root.left;//实例变量直接赋值来定义
System.out.print(root.data);
root.left = root.right;
root.right = contain;
invertTree(root.left);//遍历节点的左孩子
invertTree(root.right);//遍历节点的右孩子,一个都不能少
return root;
/*对比别人的
TreeNode temp = root.left;
root.left = invertTree(root.right);
root.right = invertTree(temp);
return root;
*/
}
public static void main(String[] args) {
// TODO 自动生成的方法存根
InvertTree226 tree = new InvertTree226();
tree.creatBinaryTree();
TreeNode root = tree.list.get(0);
TreeNode node = tree.invertTree(root);
//System.out.print(node.right.right.data);//到底怎么输出啊
}
}
想要向系统输入测试用例一样输入[4,2,3,6,null,4,8]什么的,但是用Integar[] 数组来定义,又不对,哭了