非递归中序遍历

简介: 非递归思想
class Solution {
    public int i = 0;
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        i = postorder.length-1;
        if(inorder == null || postorder == null){
            return null;
        }
        return buildTreeChild(inorder,postorder,0,postorder.length-1);
    }
    public TreeNode buildTreeChild(int[] inorder,int[] postorder,
    int inbegin,int inend){
        if(inbegin > inend){
            return null;
        }
        TreeNode root = new TreeNode(postorder[i]);
        //逗号写成了点号,一定要注意细节
        int rootIndex = findIndex(inorder,inbegin,inend,postorder[i]);
        i--;
        root.right = buildTreeChild(inorder,postorder,rootIndex + 1,inend);
        root.left = buildTreeChild(inorder,postorder,inbegin,rootIndex - 1);
        return root;
    }
    public int findIndex(int[] inorder,int begin,int inend,int key){
        for(int i =begin;i<= inend;i++){
            if(inorder[i] == key){
                return i;
            }
        }
        return -1;
    }
}
相关文章
|
4月前
二叉树的前序遍历、中序遍历、后序遍历
二叉树的前序遍历、中序遍历、后序遍历
|
3月前
|
存储
LeetCode题94,44,145,二叉树的前中后序遍历,非递归
LeetCode题94,44,145,二叉树的前中后序遍历,非递归
34 0
|
10月前
1339:【例3-4】求后序遍历
1339:【例3-4】求后序遍历
|
12月前
|
存储
非递归方式实现二叉树的前、中、后序遍历
非递归方式实现二叉树的前、中、后序遍历
【C++】非递归实现二叉树的前中后序遍历
【C++】非递归实现二叉树的前中后序遍历
【C++】非递归实现二叉树的前中后序遍历
|
存储 索引
根据前序遍历和[中序遍历]
根据前序遍历和[中序遍历]
78 0
|
算法 搜索推荐
从二叉树的前中后序遍历,我们来说递归和快速排序
从二叉树的前中后序遍历,我们来说递归和快速排序
从二叉树的前中后序遍历,我们来说递归和快速排序
|
C语言 C++
前序遍历+中序遍历重建二叉树
前序遍历+中序遍历重建二叉树
95 0
前序遍历+中序遍历重建二叉树
|
前端开发
二叉树与前序遍历、中序遍历、后续遍历
二叉树相关的面试题也是前端面试中非常重要的一部分。那二叉树是什么样的一种结构呢?
120 0
|
算法 前端开发 JavaScript
「LeetCode」二叉树的先中后序遍历(非递归版)⚡️
「LeetCode」二叉树的先中后序遍历(非递归版)⚡️
94 0
「LeetCode」二叉树的先中后序遍历(非递归版)⚡️