博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
106. Construct Binary Tree from Inorder and Postorder Traversal(python+cpp)
阅读量:3702 次
发布时间:2019-05-21

本文共 2169 字,大约阅读时间需要 7 分钟。

题目:

Given inorder and postorder traversal of a tree, construct the binary tree.

Note: You may assume that duplicates do not exist in the tree.

For example, given

inorder = [9,3,15,20,7] postorder = [9,15,7,20,3]

Return the following

binary tree:

3       / \     9  20    /  \       15   7

解释:

用中序遍历和后序遍历恢复二叉树。
没有前序遍历,就需要用后序遍历的最后一个元素来定位根节点了。
python代码:

# Definition for a binary tree node.# class TreeNode(object):#     def __init__(self, x):#         self.val = x#         self.left = None#         self.right = Noneclass Solution(object):    def buildTree(self, inorder, postorder):        """        :type inorder: List[int]        :type postorder: List[int]        :rtype: TreeNode        """        if not inorder:            return None        root_val=postorder[-1]        root=TreeNode(root_val)        index=inorder.index(root_val)        in_left,post_left=inorder[:index],postorder[:index]        in_right,post_right=inorder[index+1:],postorder[index:-1]        if in_left:            root.left=self.buildTree(in_left,post_left)        if in_right:            root.right=self.buildTree(in_right,post_right)        return root

c++代码:

/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {
public: TreeNode* buildTree(vector
& inorder, vector
& postorder) {
if (!inorder.size()) return NULL; int root_val=postorder[postorder.size()-1]; TreeNode* root=new TreeNode(root_val); int idx=find(inorder.begin(),inorder.end(),root_val)-inorder.begin(); vector
in_left(inorder.begin(),inorder.begin()+idx); vector
post_left(postorder.begin(),postorder.begin()+idx); vector
in_right(inorder.begin()+idx+1,inorder.end()); vector
post_right(postorder.begin()+idx,postorder.end()-1); if(in_left.size()) root->left=buildTree(in_left,post_left); if(in_right.size()) root->right=buildTree(in_right,post_right); return root; }};

总结:

emmmmmm,还是一样的套路。

转载地址:http://eglcn.baihongyu.com/

你可能感兴趣的文章
选票统计
查看>>
名单真相
查看>>
最终排名
查看>>
小鑫の日常系列故事(十)——排名次
查看>>
老--质价比
查看>>
选夫婿1
查看>>
共用体练习
查看>>
数据结构实验之链表一:顺序建立链表
查看>>
数据结构实验之链表二:逆序建立链表
查看>>
数据结构实验之链表三:链表的逆置
查看>>
数据结构实验之链表四:有序链表的归并
查看>>
数据结构实验之链表七:单链表中重复元素的删除
查看>>
师--链表的结点插入
查看>>
数据结构实验之链表五:单链表的拆分
查看>>
不敢死队问题
查看>>
约瑟夫问题
查看>>
三国佚事——巴蜀之危
查看>>
养兔子
查看>>
C语言实验——拍皮球
查看>>
母牛的故事
查看>>