北京天通苑网站建设做网站公司报价
news/
2025/10/5 18:12:30/
文章来源:
北京天通苑网站建设,做网站公司报价,徐州网页,搞定设计在线制作这是树的第10篇算法#xff0c;力扣链接。 给定两个整数数组 inorder 和 postorder #xff0c;其中 inorder 是二叉树的中序遍历#xff0c; postorder 是同一棵树的后序遍历#xff0c;请你构造并返回这颗 二叉树 。 示例 1: 输入#xff1a;inorder [9,3,15,20,7], po…这是树的第10篇算法力扣链接。 给定两个整数数组 inorder 和 postorder 其中 inorder 是二叉树的中序遍历 postorder 是同一棵树的后序遍历请你构造并返回这颗 二叉树 。 示例 1: 输入inorder [9,3,15,20,7], postorder [9,15,7,20,3]
输出[3,9,20,null,null,15,7] 回忆一下中序遍历和后序遍历。 中序遍历 (Inorder Traversal) 在中序遍历中我们按照以下顺序遍历树中的节点 遍历左子树访问根节点遍历右子树 对于二叉搜索树BST中序遍历会按照升序访问所有节点因为二叉搜索树的特点是左子节点的值小于根节点的值根节点的值小于右子节点的值。 后序遍历 (Postorder Traversal) 后序遍历的顺序是 遍历左子树遍历右子树访问根节点 后序遍历常用于删除或释放树中的节点。因为你在删除节点之前先访问其子节点这样可以安全地删除每个节点。 假设有一棵二叉树如下 A/ \B C/ \ \
D E F对这棵树进行不同的遍历会得到以下结果 中序遍历D, B, E, A, C, F。首先遍历左子树D, B, E然后是根节点A最后是右子树C, F。后序遍历D, E, B, F, C, A。首先是左子树D, E, B然后是右子树F, C最后是根节点A。 这道题和上一篇算法的前序遍历类似这不过这里的后序遍历涉及到一定的逆逻辑例如根节点是最后一个节点右子树的范围到 len(postorder)-1-len(inorder[index1:])
func buildTree(inorder []int, postorder []int) *TreeNode {if len(postorder) 0 {return nil}index : 0for ; index len(inorder); index {if inorder[index] postorder[len(postorder)-1] {break}}result : TreeNode{Val: postorder[len(postorder)-1]}result.Right buildTree(inorder[index1:], postorder[len(postorder)-1-len(inorder[index1:]):len(postorder)-1])result.Left buildTree(inorder[:index], postorder[:len(postorder)-1-len(inorder[index1:])])return result
}当然也可以试试迭代的方法。
func buildTree(inorder []int, postorder []int) *TreeNode {if len(postorder) 0 {return nil}result : TreeNode{Val: postorder[len(postorder)-1]}stack : []*TreeNode{result}inorderIndex : len(inorder) - 1for i : len(postorder) - 2; i 0; i-- {node : stack[len(stack)-1]if node.Val ! inorder[inorderIndex] {node.Right TreeNode{Val: postorder[i]}stack append(stack, node.Right)} else {for len(stack) 0 stack[len(stack)-1].Val inorder[inorderIndex] {node stack[len(stack)-1]stack stack[:len(stack)-1]inorderIndex--}node.Left TreeNode{Val: postorder[i]}stack append(stack, node.Left)}}return result
}
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/928574.shtml
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!