国内最全IT社区平台 联系我们 | 收藏本站
华晨云阿里云优惠2
您当前位置:首页 > php开源 > php教程 > 【一天一道LeetCode】#106. Construct Binary Tree from Inorder and Postorder Traversall

【一天一道LeetCode】#106. Construct Binary Tree from Inorder and Postorder Traversall

来源:程序员人生   发布时间:2016-07-13 10:21:42 阅读次数:2119次

1天1道LeetCode

本系列文章已全部上传至我的github,地址:ZeeCoder‘s Github
欢迎大家关注我的新浪微博,我的新浪微博
欢迎转载,转载请注明出处

(1)题目

来源:https://leetcode.com/problems/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

(2)解题

本题大意:给定1个2叉树的中序和后序遍历,构造出该2叉树
思路可以参考:【1天1道LeetCode】#105. Construct Binary Tree from Preorder and Inorder Traversal
与上题1样,只不过,后序遍历的最后1个节点为根节点,然后在中序遍历中找到根节点,从而找出根节点的左右子树。
中序遍历为:左子树+根节点+右子树
后序遍历为:左子树+右子树+根节点
例如:中序遍历213,后序遍历231,根节点为1,在中序遍历中肯定2为左子树,3为右子树。
具体思路见代码:

/** * 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<int>& inorder, vector<int>& postorder) { if(inorder.empty()||postorder.empty()) return NULL;//为空则返回NULL return constructTree(inorder,postorder,0,inorder.size()-1,0,postorder.size()-1); } TreeNode* constructTree(vector<int>& inorder, vector<int>& postorder, int inStart,int inEnd,int postStart,int postEnd) { if(postStart>postEnd||inStart>inEnd) return NULL; TreeNode* root = new TreeNode(postorder[postEnd]);//根节点为后序遍历的 if(postStart==postEnd||inStart==inEnd) return root; int i ; for(i = inStart ;i<inEnd;i++)//在中序遍历中找到根节点 { if(inorder[i]==postorder[postEnd]) break; } root->left = constructTree(inorder,postorder,inStart,i-1,postStart,postStart+i-inStart-1);//构造左子树 root->right = constructTree(inorder,postorder,i+1,inEnd,postStart+i-inStart,postEnd-1);//构造右子树 return root; } };
生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠
程序员人生
------分隔线----------------------------
分享到:
------分隔线----------------------------
关闭
程序员人生