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

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

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


/*
 * public 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 int[][] threeOrders (TreeNode root) {
        // write code here
        
        int[][] result = new int[3][getNums(root)];
       
        order(result,root);
        return result;
        
    }
            //先序
    int flag = 0,flag1= 0,flag2 = 0;
    public void order(int[][] data,TreeNode node){
        if(node == null){
            return;
        }
        data[0][flag ++] = node.val;
        order(data, node.left);
        data[1][flag1 ++] = node.val;
        order(data, node.right);
        data[2][flag2 ++] = node.val;
    }
      public int getNums(TreeNode root){
         if(root == null){
             return 0;
         }
          return 1 +getNums(root.left) +getNums(root.right);
    }
}
全部评论

相关推荐

头顶尖尖的程序员:我也是面了三四次才放平心态的。准备好自我介绍,不一定要背熟,可以记事本写下来读。全程控制语速,所有问题都先思考几秒,不要急着答,不要打断面试官说话。
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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