LeetCode 106: Construct Binary Tree from Inorder and Postorder Traversal
2015-10-28 10:13
375 查看
Construct Binary Tree from Inorder and Postorder Traversal
Given inorder and postorder traversal of a tree, construct the binary tree.Note:
You may assume that duplicates do not exist in the tree.
解题思路
方法和 LeetCode 105 类似,不过这里要利用后序序列的最后一个数字一定是树的根的性质。代码如下:/** * 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 { TreeNode* buildTree(vector<int>& inorder, int il, int ir, vector<int>& postorder, int pl, int pr) { if (pl >= pr) return NULL; // 构造根节点 TreeNode *root = new TreeNode(postorder[pr-1]); // 左子树大小 int leftSize = 0; while (inorder[il + leftSize] != postorder[pr-1]) leftSize++; // 递归构造左子树 root->left = buildTree(inorder, il, il + leftSize, postorder, pl, pl + leftSize); // 递归构造右子树 root->right = buildTree(inorder, il + leftSize + 1, ir, postorder, pl + leftSize, pr - 1); return root; } public: TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) { return buildTree(inorder, 0, inorder.size(), postorder, 0, postorder.size()); } };
相关文章推荐
- AVL树-自平衡二叉查找树(Java实现)
- C语言二叉树的非递归遍历实例分析
- 使用C语言构建基本的二叉树数据结构
- C++非递归队列实现二叉树的广度优先遍历
- C#使用前序遍历、中序遍历和后序遍历打印二叉树的方法
- C#非递归先序遍历二叉树实例
- C++非递归建立二叉树实例
- C语言实现找出二叉树中某个值的所有路径的方法
- C++实现二叉树遍历序列的求解方法
- C语言实现二叉树遍历的迭代算法
- 用C语言判断一个二叉树是否为另一个的子结构
- C++实现二叉树非递归遍历方法实例总结
- C++二叉树结构的建立与基本操作
- 深入遍历二叉树的各种操作详解(非递归遍历)
- JavaScript数据结构和算法之二叉树详解
- java使用归并删除法删除二叉树中节点的方法
- Java中二叉树数据结构的实现示例
- python数据结构之二叉树的建立实例
- python数据结构树和二叉树简介
- python数据结构之二叉树的统计与转换实例