SwaraAdam

untukMuhib

Jul 29th, 2021
623
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. main() {
  2.   var leaf1 = Node("leaf1", 9, null, null);
  3.   var leaf2 = Node("leaf2", 5, null, null);
  4.   var leaf3 = Node("leaf3", 6, null, null);
  5.   var leaf4 = Node("leaf4", 7, null, null);
  6.  
  7.   var branch1 = Node("branch1", 4, leaf1, null);
  8.   var branch2 = Node("branch2", 2, branch1, leaf2);
  9.   var branch3 = Node("branch4", 3, leaf3, leaf4);
  10.  
  11.   var root = Node("root", 1, branch2, branch3);
  12.  
  13.   List<Node> nodes = [
  14.     leaf1,
  15.     leaf2,
  16.     leaf3,
  17.     leaf4,
  18.     branch1,
  19.     branch2,
  20.     branch3,
  21.     root
  22.   ];
  23.  
  24.   List<int?> res = [];
  25.   int n = 4;
  26.  
  27.   printRes(mappingList(leaf1, nodes),n, res);
  28.   printRes(mappingList(leaf2, nodes),n, res);
  29.   printRes(mappingList(leaf3, nodes),n, res);
  30.   printRes(mappingList(leaf4, nodes),n, res);
  31.  
  32.   print(res.toSet());
  33.  
  34. }
  35.  
  36.  
  37. void printRes(List<int?> _list, int n, List<int?> res){
  38.   if(_list.length >= n){
  39.     res.add(_list[n-1]);
  40.   }
  41. }
  42.  
  43. List<int?> mappingList(Node _leaf, List<Node> _list) {
  44.   List<int?> temp = [];
  45.  
  46.   bool isRoot = false;
  47.   Node? currentLeaf = _leaf;
  48.  
  49.   while (!isRoot) {
  50.     _list.forEach((item) {
  51.       if(item.left != null && currentLeaf!.name == item.left!.name){
  52.         temp.add(item.value);
  53.         currentLeaf = item;
  54.         return;
  55.       }
  56.      
  57.       if(item.right != null && currentLeaf!.name == item.right!.name){
  58.         temp.add(item.value);
  59.         currentLeaf = item;
  60.         return;
  61.       }
  62.      
  63.       isRoot = true;
  64.      
  65.     });
  66.   }
  67.   return temp;
  68. }
  69.  
  70. class Node {
  71.   String name = "yes";
  72.   int? value;
  73.   Node? left;
  74.   Node? right;
  75.  
  76.   Node(String name, int? value, Node? left, Node? right) {
  77.     this.name = name;
  78.     this.value = value;
  79.     this.left = left;
  80.     this.right = right;
  81.   }
  82. }
  83.  
RAW Paste Data