---
# System prepended metadata

title: 2196. Create Binary Tree From Descriptions
tags: [Leetcode, Tree, Medium]

---

# 2196. Create Binary Tree From Descriptions
###### tags: `Leetcode` `Medium` `Tree`
Link: https://leetcode.com/problems/create-binary-tree-from-descriptions/description/
## 思路
通过每个description建subtree非常好实现
问题是如何找到root
这里用的方法是如果一个parent从来没有出现在children的位置 那么它就是root
## Code
```java=
class Solution {
    public TreeNode createBinaryTree(int[][] descriptions) {
        Set<Integer> children = new HashSet<>();
        TreeNode root = null;
        Map<Integer, TreeNode> map = new HashMap<>();
        for(int[] description:descriptions){
            children.add(description[1]);
            TreeNode parent = null, child = null;
            if(!map.containsKey(description[0])){
                parent = new TreeNode(description[0]);
                map.put(description[0], parent);
            }
            parent = map.get(description[0]);
            if(!map.containsKey(description[1])){
                child = new TreeNode(description[1]);
                map.put(description[1], child);
            }
            child = map.get(description[1]);
            if(description[2]==1) parent.left = child;
            else parent.right = child;
        }
        for(int[] description:descriptions){
            if(!children.contains(description[0])){
                root = map.get(description[0]);
                break;
            }
        }
        return root;
    }
}
```