Advertisement
Guest User

Leetcode 2196 - Create Binary Tree From Descriptions

a guest
Mar 6th, 2022
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.12 KB | None | 0 0
  1. // Credit: https://leetcode.com/hank55663/ from https://leetcode.com/contest/weekly-contest-283/ranking/ problem C
  2. // Added comment
  3. class Solution {
  4. public:
  5.     int l[100005],r[100005]; // l[i] -> i 的左子節點; r[i] -> i 的右子節點. 0 代表沒有
  6.     int cnt[100005]; // 當過 child 的次數
  7.     TreeNode *build(int x){
  8.         TreeNode *res = new TreeNode(x);
  9.         if(l[x])
  10.             res->left = build(l[x]);
  11.         if(r[x])
  12.             res->right = build(r[x]);
  13.         return res;
  14.     }
  15.     TreeNode* createBinaryTree(vector<vector<int>>& descriptions) {
  16.         // init
  17.         for(auto it:descriptions){
  18.             l[it[0]] = r[it[0]] = l[it[1]] = r[it[1]] = 0;
  19.         }
  20.  
  21.         // 建表
  22.         for(auto it:descriptions){
  23.             if(it[2])
  24.                 l[it[0]] = it[1];
  25.             else
  26.                 r[it[0]] = it[1];
  27.             cnt[it[1]]++;
  28.         }
  29.  
  30.         // 建樹
  31.         for(auto it:descriptions){
  32.             if(cnt[it[0]] == 0){ // 如果沒當過 child => 是 root
  33.                 return build(it[0]);
  34.             }
  35.         }
  36.         return NULL;
  37.     }
  38. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement