今日份牛客==分别按照二叉树先序,中序和后序打印所有的节点=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整型二维数组
     */
    public int[][] threeOrders (TreeNode root) {
     
        int n = lengthOfTreeNode(root);
        int[][] ret = new int[3][n];
        if(root == null) return ret;
        preorder(root, ret);
        inorder(root, ret);
        postorder(root, ret);
        return ret;
    }
    public int lengthOfTreeNode(TreeNode root){
     
        if(root == null) return 0;
        return lengthOfTreeNode(root.left) + lengthOfTreeNode(root.right) + 1;
    }
    public void preorder(TreeNode root, int[][]ret){
     
        Stack<TreeNode> stack = new Stack<>();
        int index = 0;
        while(root != null || !stack.isEmpty()){
     
            while(root != null){
     
                ret[0][index++] = root.val;
                stack.push(root);
                root = root.left;
            }
            if(!stack.isEmpty()){
     
                root = stack.pop();
                root = root.right;
            }
        }
    }
    public void inorder(TreeNode root, int[][]ret){
     
        Stack<TreeNode> stack = new Stack<>();
        int index = 0;
        while(root != null || !stack.isEmpty()){
     
            while(root != null){
     
                stack.push(root);
                root = root.left;
            }
            if(!stack.isEmpty()){
     
                root = stack.pop();
                ret[1][index++] = root.val;
                root = root.right;
            }
        }
    }
    public void postorder(TreeNode root, int[][]ret){
     
        Stack<TreeNode> s1 = new Stack<>();
        Stack<TreeNode> s2 = new Stack<>();
        s1.push(root);
        int index = 0;
        while(!s1.isEmpty()){
     
            root = s1.pop();
            s2.push(root);
            if(root.left != null) s1.push(root.left);
            if(root.right != null) s1.push(root.right);
        }
        while(!s2.isEmpty()){
     
            ret[2][index++] = s2.pop().val;
        }
    }
}

你可能感兴趣的:(今日份牛客,算法,二叉树,java)