You are given a 2D integer array descriptions where descriptions[i] = [parenti, childi, isLefti] indicates that parenti is the parent of childi in a binary tree of unique values. Furthermore,
If isLefti == 1, then childi is the left child of parenti.
If isLefti == 0, then childi is the right child of parenti.
Construct the binary tree described by descriptions and return its root.
The test cases will be generated such that the binary tree is valid.
Example 1:
Input: descriptions = [[20,15,1],[20,17,0],[50,20,1],[50,80,0],[80,19,1]]
Output: [50,20,80,15,17,19]
Explanation: The root node is the node with value 50 since it has no parent.
The resulting binary tree is shown in the diagram.
Example 2:
Input: descriptions = [[1,2,1],[2,3,0],[3,4,1]]
Output: [1,2,null,null,3,4]
Explanation: The root node is the node with value 1 since it has no parent.
The resulting binary tree is shown in the diagram.
Constraints:
1 <= descriptions.length <= 104
descriptions[i].length == 3
1 <= parent, child <= 105
0 <= isLeft <= 1
The binary tree described by descriptions is valid.
根據描述建立二叉樹。
給你一個二維整數陣列 descriptions ,其中 descriptions[i] = [parent, child, isLeft] 表示 parent 是 child 在 二叉樹 中的 父節點,二叉樹中各節點的值 互不相同 。此外:如果 isLeft == 1 ,那麼 child 就是 parent 的左子節點。
如果 isLeft == 0 ,那麼 child 就是 parent 的右子節點。
請你根據 descriptions 的描述來構造二叉樹並返回其 根節點 。測試用例會保證可以構造出 有效 的二叉樹。
思路
思路是雜湊表 + 模擬。遍歷 input 陣列,因為題目說了二叉樹中各節點的值互不相同,所以這裡我們可以用一個雜湊表記錄<node val, TreeNode>的關係。因為每個 description 展示的是兩個 node 之間的關係,所以在用雜湊表存好<node val, TreeNode>之後,我們還可以連線這兩個節點,以儲存節點之間的父子關係。
這裡同時我用了一個 visited 陣列,記錄所有遍歷到的 child 節點。最後我再次遍歷這個 visited 陣列的時候,唯一一個沒有被遍歷到的值就是根節點的值 root.val,所以最後返回的是 map.get(root.val) 就是根節點。
複雜度
時間O(n)
空間O(n)
程式碼
Java實現
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode createBinaryTree(int[][] descriptions) {
HashMap<Integer, TreeNode> map = new HashMap<>();
int[] visited = new int[100001];
for (int i = 0; i < descriptions.length; i++) {
int parent = descriptions[i][0];
int child = descriptions[i][1];
int isLeft = descriptions[i][2];
if (!map.containsKey(parent)) {
TreeNode node = new TreeNode(parent);
map.put(parent, node);
}
if (!map.containsKey(child)) {
TreeNode node = new TreeNode(child);
map.put(child, node);
}
// build parent, child relationship
TreeNode p = map.get(parent);
TreeNode c = map.get(child);
// visited陣列記錄所有遍歷過的child node
visited[child] = 1;
if (isLeft == 1) {
p.left = c;
} else {
p.right = c;
}
}
TreeNode root = new TreeNode();
for (Integer i : map.keySet()) {
if (visited[i] == 0) {
root = map.get(i);
return root;
}
}
return null;
}
}