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

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

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

import java.util.*;

/*
 * 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) {
       int sum = count(root);
       int [][] array = new int [3][sum];
        ArrayList array1 = new ArrayList<Integer>();
        first(root,array1);
        middle(root,array1);
        after(root,array1);
        // write code here
        int s = 0;
        for(int i = 0;i<array.length;i++){
            for(int j=0;j<array[i].length;j++){
                array[i][j]=(int)array1.get(s);
                s++;
            }
        }
        return array;
    }
    
    //计算节点个数
   public int count(TreeNode root){
       if(root==null){
           return 0;
       }else{
         int leftCount = count(root.left);
         int rightCount = count(root.right);
         return leftCount+rightCount+1;
       }
   }
    
    //前序递归遍历
   public void first(TreeNode root,ArrayList array){
       if(root != null){
           array.add(root.val);
           first(root.left,array);
           first(root.right,array);
       }
       
   }
    //中序递归遍历
   public void middle(TreeNode root,ArrayList array){
     if(root != null){
           middle(root.left,array);
           array.add(root.val);
           middle(root.right,array);
       }
   }
    //后续递归遍历
   public void after(TreeNode root,ArrayList array){
       if(root!=null){
           after(root.left,array);
           after(root.right,array);
           array.add(root.val);
       }
   }
}
全部评论

相关推荐

点赞 评论 收藏
分享
白火同学:大二有这水平很牛了,可以适当对关键信息加粗一点,比如关键技术、性能指标之类的。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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