leetcode刷題筆記一百零六題 從中序與後序遍歷序列構造二叉樹
阿新 • • 發佈:2020-08-04
leetcode刷題筆記一百零六題 從中序與後序遍歷序列構造二叉樹
問題描述:
根據一棵樹的中序遍歷與後序遍歷構造二叉樹。
注意: 你可以假設樹中沒有重複的元素。
例如,給出
中序遍歷 inorder = [9,3,15,20,7] 後序遍歷 postorder = [9,15,7,20,3] 返回如下的二叉樹:
3
/
9 20 /
15 7
/** 與105題解法類似,只不過根節點通過後序遍歷的尾結點判斷 */ /** * Definition for a binary tree node. * class TreeNode(var _value: Int) { * var value: Int = _value * var left: TreeNode = null * var right: TreeNode = null * } */ object Solution { def buildTree(inorder: Array[Int], postorder: Array[Int]): TreeNode = { val inorderLen = inorder.length val postorderLen = postorder.length if (inorderLen != postorderLen) return null def helper(inorder: Array[Int], postorder: Array[Int], inLeft: Int, inRight: Int, postLeft: Int, postRight: Int): TreeNode = { //遞迴終止條件 if (inLeft > inRight || postLeft > postRight) return null val povit = postorder(postRight) val root = new TreeNode(povit) val povitIndex = inorder.indexOf(povit) root.left = helper(inorder, postorder, inLeft, povitIndex-1, postLeft, postRight - (inRight - povitIndex)-1) root.right = helper(inorder, postorder, povitIndex+1, inRight, postLeft+povitIndex-inLeft, postRight-1) return root } return helper(inorder, postorder, 0, inorderLen-1, 0, postorderLen-1) } }