加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

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

发布时间:2020-12-13 21:11:12 所属栏目:PHP教程 来源:网络整理
导读:1天1道LeetCode 本系列文章已全部上传至我的github,地址:ZeeCoder‘s Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 (1)题目 来源:https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traver

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,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,inStart,i-1,postStart,postStart+i-inStart-1);//构造左子树 root->right = constructTree(inorder,i+1,inEnd,postStart+i-inStart,postEnd-1);//构造右子树 return root; } };

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读