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);
        }
    }
  • 相关阅读:
    单据存储过程
    C语言II博客作业04
    C语言II博客作业03
    C语言II博客作业02
    C语言II博客作业01
    学期总结
    C语言I博客作业09
    C语言I博客作业08
    C语言I博客作业07
    C语言I博客作业06
  • 原文地址:https://www.cnblogs.com/jieran/p/14487381.html
Copyright © 2011-2022 走看看