题解 | #实现二叉树先序,中序和后序遍历#

实现二叉树先序,中序和后序遍历

http://www.nowcoder.com/practice/a9fec6c46a684ad5a3abd4e365a9d362

import java.util.;
// class TreeNode {
// int val = 0;
// TreeNode left = null;
// TreeNode right = null;
// }
public class Solution {
/*

*
* @param root TreeNode类 the root of binary tree
* @return int整型二维数组
*/
public static class ID{
public int num;
public ID(int i){
num = i;
}
public int add(){
this.num += 1;
return this.num;
}
}

public static int[][] threeOrders (TreeNode root) {
    // write code here
    // 分别按照二叉树先序,中序和后序打印所有的节点。
    int length = 0;
    length = num(root);
    int[][] arr = new int[3][length];
    preOrder(root, arr, new ID(0));
    midOrder(root, arr, new ID(0));
    postOrder(root, arr, new ID(0));
    return arr;
}
public static int num(TreeNode root){
    if(root == null){
        return 0;
    }
    else{
        int a = num(root.left);
        int b = num(root.right);
        return 1+a+b;
    }
}

public static void preOrder(TreeNode root, int[][] arr, ID i){
    if(root == null){
       return;
    }
    arr[0][i.add() - 1] = root.val;
    preOrder(root.left, arr, i);
    preOrder(root.right, arr, i);
}

public static void midOrder(TreeNode root, int[][] arr, ID i){
    if(root == null){
       return;
    }
    midOrder(root.left, arr, i);
    arr[1][i.add() - 1] = root.val;
    midOrder(root.right, arr, i);
}
public static void postOrder(TreeNode root, int[][] arr, ID i){
    if(root == null){
       return;
    }
    postOrder(root.left, arr, i);
    postOrder(root.right, arr, i);
    arr[2][i.add() - 1] = root.val;
}

}

全部评论

相关推荐

乐观的打工人前程似锦:怎么说呢🤔️,学历够,专业技能看起来也有那么回事,就是项目会不会差点?dji更喜欢较为复杂的工程落地的项目吧?如果有一些title的项目就更好了。有实习也是加分项,搞过神经网络应该也是加分项。进面应该可以,还是要看技术过硬
点赞 评论 收藏
分享
2024-12-27 23:45
已编辑
三江学院 Java
程序员牛肉:死局。学历+无实习+项目比较简单一点。基本就代表失业了。 尤其是项目,功能点实在是太假了。而且提问点也很少。第一个项目中的使用jwt和threadlocal也可以作为亮点写出来嘛?第二个项目中的“后端使用restful风格”,“前端采用vue.JS”,“使用redis”也可以作为亮点嘛? 项目实在是太简单了,基本就是1+1=2的水平。而你目标投递的肯定也是小厂,可小厂哪里有什么培养制度,由于成本的问题,人家更希望你来能直接干活,所以你投小厂也很难投。基本就是死局,也不一定非要走后端这条路。可以再学一学后端之后走测试或者前端。 除此之外,不要相信任何付费改简历的。你这份简历没有改的必要了,先沉淀沉淀
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务