根据树的后序遍历和中序遍历构造二叉树

根据一棵树的后序遍历与中序遍历构造二叉树

思路及实现:
1.先遍历后序,从尾巴开始倒着遍历(倒数第一个元素为根节点)
2.找到后序遍历的节点在中序当中的位置
3.一直去遍历后序

从后向前遍历后序遍历数组;
拿到后序遍历的倒数第一个节点,new一个节点出来让其成为根节点;
找到在中序遍历数组中该节点的位置,左边就是左子树,右边就是右子树;
继续上述查找,直到后序遍历结果的数组全部遍历完。

 public int posIndex = 0;
    public Node buildTreeChild2 (int[] postorder,int[] inorder,int inbegin,int inend){
        if(inbegin > inend){
            return null;
        }
        Node root = new Node(postorder[posIndex]);
        int rootIndex = findInorderIndex(inorder,inbegin,inend,postorder[posIndex]);
        if(rootIndex == -1){
            return null;
        }
        posIndex--;
        root.right = buildTreeChild2(postorder,inorder,rootIndex+1,inend);
        root.left = buildTreeChild2(postorder,inorder,inbegin,rootIndex-1);
        return root;
    }

    public Node buildTree2 (int[] postorder,int[] inorder){
        if(postorder.length == 0 || inorder.length == 0){
            return null;
        }
        posIndex = postorder.length-1;
        return buildTreeChild2(postorder,inorder,0,inorder.length-1);
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
根据给定的后序遍历中序遍历,可以构造二叉树,然后再进行前序遍历输出。具体步骤如下: 1.定义一个TreeNode类,包含val、left、right三个属性,用于表示二叉树的节点。 2.定义一个函数buildTree,接收两个参数inorder和postorder,分别表示中序遍历后序遍历。 3.在buildTree函数中,首先判断inorder和postorder是否为空,如果为空,则返回None。 4.然后从postorder中取出最后一个元素,作为当前子的根节点。 5.在inorder中找到根节点的位置,将inorder分成左子和右子两部分。 6.递归调用buildTree函数,分别传入左子中序遍历后序遍历,以及右子中序遍历后序遍历,得到左子和右子的根节点。 7.将左子和右子的根节点分别作为当前根节点的左右子节点。 8.最后返回当前根节点。 9.定义一个函数preorderTraversal,接收一个参数root,表示二叉树的根节点。 10.在preorderTraversal函数中,首先判断root是否为空,如果为空,则返回空列表。 11.然后按照根节点、左子、右子的顺序进行前序遍历,将遍历结果存入列表中。 12.最后返回列表。 下面是完整的代码实现: ```python class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def buildTree(inorder, postorder): if not inorder or not postorder: return None root_val = postorder[-1] root = TreeNode(root_val) index = inorder.index(root_val) left_inorder = inorder[:index] right_inorder = inorder[index+1:] left_postorder = postorder[:index] right_postorder = postorder[index:-1] root.left = buildTree(left_inorder, left_postorder) root.right = buildTree(right_inorder, right_postorder) return root def preorderTraversal(root): if not root: return [] res = [root.val] res += preorderTraversal(root.left) res += preorderTraversal(root.right) return res inorder = [9,3,15,20,7] postorder = [9,15,7,20,3] root = buildTree(inorder, postorder) print(preorderTraversal(root)) # 输出:[3, 9, 20, 15, 7] ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值