从前序与中序遍历序列构造二叉树[迭代]Day-12

从前序与中序遍历序列构造二叉树[迭代]

给定两个整数数组 preorder 和 inorder ,其中 preorder 是二叉树的先序遍历, inorder 是同一棵树的中序遍历,请构造二叉树并返回其根节点。

示例 1:

输入: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
输出: [3,9,20,null,null,15,7]

示例 2:

输入: preorder = [-1], inorder = [-1]
输出: [-1]

题解

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        //迭代
        if(preorder == null || preorder.length == 0){
            return null;
        }
        //根节点root
        TreeNode root = new TreeNode(preorder[0]);
        //定义队列,栈的方法队列都有
        Deque<TreeNode> stack = new LinkedList<TreeNode>();
        //根节点加入栈
        stack.push(root);
        //遍历中序数组索引用
        int startindex = 0;
        //循环前序数组preorder
        for(int i = 1; i < preorder.length; ++i){
            //值赋值给变量preoderVal
            int preorderVal = preorder[i];
            //栈顶元素称为二叉树节点
            TreeNode node = stack.peek();
            //中序数组不等于栈顶元素值
            if(inorder[startindex] != node.val){
                //让节点值变成二叉树节点,再赋值给node的左节点
                node.left = new TreeNode(preorderVal);
                //加入栈
                stack.push(node.left);
            }else{
                //如果栈顶元素相等就弹出
                while(!stack.isEmpty() && inorder[startindex] == stack.peek().val){
                    node = stack.pop();
                    //中序数组的索引加一
                    startindex++;
                }
                //如果不符合就说明是右节点,添加即可
                node.right = new TreeNode(preorderVal);
                //入栈
                stack.push(node.right);
            }
        }
        return root;
    }
}

你可能感兴趣的:(算法top100,leetcode,数据结构,算法)