日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Construct Binary Tree from Preorder and Inorder Traversal

發布時間:2025/3/19 编程问答 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Construct Binary Tree from Preorder and Inorder Traversal 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Given preorder and inorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.

?

ref:?http://fisherlei.blogspot.com/2013/01/leetcode-construct-binary-tree-from.html

注意 preorder根節點的下標是 pStart, 不要寫成 0

?注意 preorder 注意左子樹和右子樹開始的index

左子樹是 pStart+1 + (rootIndex-1 - iStart) // inorder中 左子樹的長度

右子樹是?pStart+1 + (rootIndex-1 - iStart) +1

?

/*** Definition for binary tree* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode(int x) { val = x; }* }*/ public class Solution {public TreeNode buildTree(int[] preorder, int[] inorder) {if (preorder == null || inorder == null) {return null;}int preLen = preorder.length;int inLen = inorder.length;if (preLen == 0 || inLen == 0) {return null;}return constructTree(preorder, 0, preLen - 1, inorder, 0, inLen - 1);}public static TreeNode constructTree(int[] preorder, int preStart, int preEnd,int[] inorder, int inStart, int inEnd) {int rootValue = preorder[preStart];TreeNode root = new TreeNode(rootValue);root.left = null;root.right = null;if (preStart == preEnd && preorder[preStart] == inorder[inStart]) {return root;}int i = inStart;for (; i <= inEnd; i++) {if (rootValue == inorder[i]) {break;}}int leftLen = i - inStart;// 如果左子樹不為空if (leftLen > 0) {root.left = constructTree(preorder, preStart + 1, preStart+ leftLen, inorder, inStart, i - 1);}// 如果右子樹不為空if (inEnd > i) {root.right = constructTree(preorder, preStart + leftLen + 1,preEnd, inorder, i + 1, inEnd);}return root;}}

?

轉載于:https://www.cnblogs.com/RazerLu/p/3545284.html

總結

以上是生活随笔為你收集整理的Construct Binary Tree from Preorder and Inorder Traversal的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。