zoukankan      html  css  js  c++  java
  • 实现二叉树先序,中序,后序

    题目描述:

    分别按照二叉树先序,中序,后序打印所有的节点

    输入:

    {1,2,3}

    返回值

    [[1,2,3],[2,1,3],[2,3,1]]

    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整型二维数组
         */
        private int preIndex = 0;
        private int inIndex = 0;
        private int postIndex = 0;
        
        public int[][] threeOrders (TreeNode root) {
            // write code here
            // 前序
            int size = getNums(root);
            
            int[][] res = new int[3][size];
            preOrder(root,res);
            inOrder(root,res);
            postOrder(root,res);
            return res;
        }
        public void postOrder(TreeNode root,int[][] res){
            if(root == null){
                return;
            } 
            postOrder(root.left,res);
            postOrder(root.right,res);
            res[2][postIndex++] = root.val;
        }
        
        public void inOrder(TreeNode root,int[][] res){
            if(root == null){
                return;
            } 
            inOrder(root.left,res);
            res[1][inIndex++] = root.val;
            inOrder(root.right,res);
        }
        
        public void preOrder(TreeNode root,int[][] res){
            if(root == null){
                return;
            } 
            res[0][preIndex++] = root.val;
            preOrder(root.left,res);
            preOrder(root.right,res);
        }
        
        
        public int getNums(TreeNode root){
            if (root == null ){
                return 0;
            }
                /*
                root  TreeNode@7d4991ad
                root.left  TreeNode@28d93b30
                root.right  TreeNode@1b6d3586
    
                root  TreeNode@28d93b30
                root.left  null
                root.right  null
    
                root  TreeNode@1b6d3586
                root.left  null
                root.right  null
    
            */
            System.out.println("root  " + root);
            System.out.println("root.left  " + root.left);
            System.out.println("root.right  " + root.right);
            return 1 + getNums(root.left) + getNums(root.right);
        }
    }
  • 相关阅读:
    BZOJ 3997: [TJOI2015]组合数学 [偏序关系 DP]
    [Sdoi2017]新生舞会 [01分数规划 二分图最大权匹配]
    [Sdoi2017]相关分析 [线段树]
    [Sdoi2017]硬币游戏 [高斯消元 KMP]
    [Sdoi2017]序列计数 [矩阵快速幂]
    [Sdoi2017]树点涂色 [lct 线段树]
    [Sdoi2017]数字表格 [莫比乌斯反演]
    BZOJ 3160: 万径人踪灭 [fft manacher]
    Rabbitmq常见测试
    MQ(消息队列)功能介绍
  • 原文地址:https://www.cnblogs.com/jieran/p/14487381.html
Copyright © 2011-2022 走看看