ann8497

MinimumDistanceLeaf Samsung

Aug 22nd, 2019
875
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.04 KB | None | 0 0
  1. /*
  2.           10
  3.         /     \
  4.       12       13
  5.            /     \
  6.          14       15    
  7.         /   \     /  \
  8.        21   22   23   24
  9.        /\   /\   /\   /\
  10.       1 2  3 4  5 6  7  8
  11. */
  12.  
  13. #include<iostream>
  14. using namespace std;
  15.  
  16. class Node{
  17.   public:
  18.   int data;
  19.   Node*left;
  20.   Node*right;
  21.     Node(int data){
  22.         data = data;
  23.         left = right = NULL;
  24.     }
  25. };
  26.  
  27.  
  28. void leaf(Node*x, int val, int *ans){
  29.    
  30.     if(x == NULL)return;
  31.    
  32.     if(!x->left && !x->right){
  33.         *ans = min(*ans, val);
  34.          return;
  35.     }  
  36.    
  37.     leaf(x->left, val+1, ans);
  38.     leaf(x->right, val+1, ans);
  39.    
  40. }
  41.  
  42. bool parent(Node* root, Node*x, int *ans){
  43.    
  44.     if(root == NULL)return false;
  45.     if(root == x)return true;
  46.    
  47.     bool l = parent(root->left, x, ans);
  48.     if(l){
  49.         leaf(root->right, 2, ans);
  50.     }
  51.    
  52.     bool r = parent(root->right, x, ans);
  53.     if(r){
  54.         leaf(root->left, 2, ans);
  55.     }
  56.    
  57.     return false;
  58.    
  59. }
  60.  
  61.  
  62. void solve(Node* root, Node*x){
  63.    
  64.     int ans = 100000;
  65.    
  66.     leaf(x , 0, &ans);
  67.     parent(root, x, &ans);
  68.    
  69.     cout<<ans<<endl;
  70.    
  71. }
  72.  
  73.  
  74. int main(){
  75.    
  76.     Node *root  = new Node(1);
  77.     root->left  = new Node(12);
  78.     root->right = new Node(13);
  79.  
  80.     root->right->left   = new Node(14);
  81.     root->right->right  = new Node(15);
  82.  
  83.     root->right->left->left   = new Node(21);
  84.     root->right->left->right  = new Node(22);
  85.     root->right->right->left  = new Node(23);
  86.     root->right->right->right = new Node(24);
  87.  
  88.     root->right->left->left->left  = new Node(1);
  89.     root->right->left->left->right = new Node(2);
  90.     root->right->left->right->left  = new Node(3);
  91.     root->right->left->right->right = new Node(4);
  92.     root->right->right->left->left  = new Node(5);
  93.     root->right->right->left->right = new Node(6);
  94.     root->right->right->right->left = new Node(7);
  95.     root->right->right->right->right = new Node(8);
  96.  
  97.     Node *x = root->right;
  98.    
  99.     solve(root,x);
  100.     return 0;
  101. }
Add Comment
Please, Sign In to add comment