今日份牛客==分别按照二叉树先序,中序和后序打印所有的节点=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;
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值