博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode-106-Construct Binary Tree from Inorder and Postorder Traversal
阅读量:7287 次
发布时间:2019-06-30

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

算法描述:

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

解题思路:理解原理,注意细节。

TreeNode* buildTree(vector
& inorder, vector
& postorder) { return helper(inorder, 0, inorder.size()-1, postorder, 0, postorder.size()-1); } TreeNode* helper(vector
& inorder, int is, int ie, vector
& postorder, int ps, int pe){ if(is > ie || ps > pe) return nullptr; TreeNode* node = new TreeNode(postorder[pe]); int pos = 0; for(int i=is; i <= ie; i++){ if(postorder[pe]==inorder[i]){ pos = i; break; } } node -> left = helper(inorder, is, pos-1, postorder, ps, ps - (is-pos+1)); node -> right = helper(inorder, pos+1, ie, postorder, ps - (is-pos+1)+1, pe-1); return node; }

 

转载于:https://www.cnblogs.com/nobodywang/p/10349592.html

你可能感兴趣的文章
jboss 优化
查看>>
Android OpenGL ES与EGL
查看>>
python中urllib和urllib2小结
查看>>
我的友情链接
查看>>
再续专注提高技术
查看>>
【Glassfish入门】使用Glassfish
查看>>
部署社交网站
查看>>
Centos7 安装JDK
查看>>
浅谈个人安全意识
查看>>
基于底层事件的录制回放实现
查看>>
ethos从入门到精通-4.1映泰主板bios设置
查看>>
js 去除字符串空白符
查看>>
我的友情链接
查看>>
UC浏览器QQ浏览器欧朋浏览器使用体会
查看>>
Tcmalloc优化Nginx内存管理
查看>>
Spring那些不得不知的细节
查看>>
java获取本机ip,mac,os名称,版本等
查看>>
P2077 红绿灯
查看>>
我的友情链接
查看>>
jsp中的回车事件
查看>>