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

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

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;
}

}

全部评论

相关推荐

05-22 12:44
已编辑
门头沟学院 golang
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务