zoukankan      html  css  js  c++  java
  • 牛客题霸NC45题解

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

    牛客题霸NC45

    难度:Easy

    题目描述

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

    示例

    输入

    {1,2,3}
    

    返回值

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

    备注:

    n≤10^6
    

    题目答案

    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) {
            // write code here
            
            List<Integer> list1 = new ArrayList<>();
            List<Integer> list2 = new ArrayList<>();
            List<Integer> list3 = new ArrayList<>();
            
            preOrder(root, list1);
            inOrder(root, list2);
            postOrder(root, list3);
            
            int[][] res = new int[3][list1.size()];
            for(int i = 0; i < list1.size(); i++){
                res[0][i] = list1.get(i);
                res[1][i] = list2.get(i);
                res[2][i] = list3.get(i);
                
            }
            
            return res;
        }
        // 先序遍历
        public void preOrder(TreeNode root, List<Integer> list){
            if(root == null){
                return;
            }
            list.add(root.val);
            preOrder(root.left, list);
            preOrder(root.right, list);
        }
        
        // 中序遍历
        public void inOrder(TreeNode root, List<Integer> list){
            if(root == null){
                return;
            }
    
            inOrder(root.left, list);
            list.add(root.val);
            inOrder(root.right, list);
        }
        
        // 后序遍历
        public void postOrder(TreeNode root, List<Integer> list){
            if(root == null){
                return;
            }
    
            postOrder(root.left, list);
            postOrder(root.right, list);
            list.add(root.val);
        }
        
    }
    
  • 相关阅读:
    让人难以想出的动态转移方程小集
    初识DP
    CSP复赛day2模拟题
    通知
    未完成作业
    2019年东莞特长生 散步
    营救
    农场主
    安全密码
    开发区规划
  • 原文地址:https://www.cnblogs.com/qwer112/p/13948449.html
Copyright © 2011-2022 走看看