logo

연속 트리

각 루트에서 리프 경로까지 인접한 두 키의 절대 차이가 1이면 트리는 연속 트리입니다. 트리가 연속인지 아닌지 확인해야 하는 이진 트리가 제공됩니다.

예: 

스캔.다음 자바
Input : 3 /  2 4 /   1 3 5 Output: 'Yes' // 3->2->1 every two adjacent node's absolute difference is 1 // 3->2->3 every two adjacent node's absolute difference is 1 // 3->4->5 every two adjacent node's absolute difference is 1 Input : 7 /  5 8 /   6 4 10 Output: 'No' // 7->5->6 here absolute difference of 7 and 5 is not 1. // 7->5->4 here absolute difference of 7 and 5 is not 1. // 7->8->10 here absolute difference of 8 and 10 is not 1.

솔루션에는 트리 순회가 필요합니다. 확인해야 할 중요한 사항은 모든 코너 케이스가 처리되었는지 확인하는 것입니다. 코너 케이스에는 빈 트리 단일 노드 트리, 왼쪽 자식만 있는 노드와 오른쪽 자식만 있는 노드가 포함됩니다.



트리 순회에서는 왼쪽과 오른쪽 하위 트리가 연속적인지 재귀적으로 확인합니다. 또한 현재 노드의 키와 하위 키의 차이가 1인지 확인합니다. 아래는 아이디어의 구현입니다.  

구현:

C++
// C++ program to check if a tree is continuous or not #include   using namespace std; /* A binary tree node has data pointer to left child  and a pointer to right child */ struct Node {  int data;  struct Node* left * right; }; /* Helper function that allocates a new node with the  given data and NULL left and right pointers. */ struct Node* newNode(int data) {  struct Node* node = new Node;  node->data = data;  node->left = node->right = NULL;  return(node); } // Function to check tree is continuous or not bool treeContinuous(struct Node *ptr) {  // if next node is empty then return true  if (ptr == NULL)  return true;  // if current node is leaf node then return true  // because it is end of root to leaf path  if (ptr->left == NULL && ptr->right == NULL)  return true;  // If left subtree is empty then only check right  if (ptr->left == NULL)  return (abs(ptr->data - ptr->right->data) == 1) &&  treeContinuous(ptr->right);  // If right subtree is empty then only check left  if (ptr->right == NULL)  return (abs(ptr->data - ptr->left->data) == 1) &&  treeContinuous(ptr->left);  // If both left and right subtrees are not empty check  // everything  return abs(ptr->data - ptr->left->data)==1 &&  abs(ptr->data - ptr->right->data)==1 &&  treeContinuous(ptr->left) &&  treeContinuous(ptr->right); } /* Driver program to test mirror() */ int main() {  struct Node *root = newNode(3);  root->left = newNode(2);  root->right = newNode(4);  root->left->left = newNode(1);  root->left->right = newNode(3);  root->right->right = newNode(5);  treeContinuous(root)? cout << 'Yes' : cout << 'No';  return 0; } 
Java
// Java program to check if a tree is continuous or not import java.util.*; class solution { /* A binary tree node has data pointer to left child and a pointer to right child */ static class Node {  int data;  Node left right; }; /* Helper function that allocates a new node with the given data and null left and right pointers. */ static Node newNode(int data) {  Node node = new Node();  node.data = data;  node.left = node.right = null;  return(node); } // Function to check tree is continuous or not static boolean treeContinuous( Node ptr) {  // if next node is empty then return true  if (ptr == null)  return true;  // if current node is leaf node then return true  // because it is end of root to leaf path  if (ptr.left == null && ptr.right == null)  return true;  // If left subtree is empty then only check right  if (ptr.left == null)  return (Math.abs(ptr.data - ptr.right.data) == 1) &&  treeContinuous(ptr.right);  // If right subtree is empty then only check left  if (ptr.right == null)  return (Math.abs(ptr.data - ptr.left.data) == 1) &&  treeContinuous(ptr.left);  // If both left and right subtrees are not empty check  // everything  return Math.abs(ptr.data - ptr.left.data)==1 &&  Math.abs(ptr.data - ptr.right.data)==1 &&  treeContinuous(ptr.left) &&  treeContinuous(ptr.right); } /* Driver program to test mirror() */ public static void main(String args[]) {  Node root = newNode(3);  root.left = newNode(2);  root.right = newNode(4);  root.left.left = newNode(1);  root.left.right = newNode(3);  root.right.right = newNode(5);  if(treeContinuous(root))  System.out.println( 'Yes') ;  else  System.out.println( 'No'); } } //contributed by Arnab Kundu 
Python
#Python Program to check continuous tree or not # A binary tree node has data pointer to left child # an a pointer to right child */ # Helper function that allocates a new node with the # given data and null left and right pointers class newNode(): def __init__(selfkey) : self.left = None self.right = None self.data = key # Function to check tree is continuous or not def treeContinuous(root): # if next node is empty then return true if not root: return True # if current node is leaf node then return true # because it is end of root to leaf path if root.left: if not abs(root.data-root.left.data)==1: return False # If right subtree is empty then only check left if root.right: if not abs(root.data-root.right.data)==1: return False # If both left and right subtrees are not empty check # everything if treeContinuous(root.left) and treeContinuous(root.right): return True # Driver code if __name__ == '__main__': root = newNode(7) root.left = newNode(6) root.right = newNode(8) root.left.left = newNode(5) root.left.right = newNode(7) root.right.right = newNode(7) print(treeContinuous(root)) 
C#
// C# program to check if a tree is continuous or not  using System; class solution  {  /* A binary tree node has data pointer to left child  and a pointer to right child */ class Node  {   public int data;   public Node left right;  };  /* Helper function that allocates a new node with the  given data and null left and right pointers. */ static Node newNode(int data)  {   Node node = new Node();   node.data = data;   node.left = node.right = null;   return(node);  }  // Function to check tree is continuous or not  static Boolean treeContinuous( Node ptr)  {   // if next node is empty then return true   if (ptr == null)   return true;   // if current node is leaf node then return true   // because it is end of root to leaf path   if (ptr.left == null && ptr.right == null)   return true;   // If left subtree is empty then only check right   if (ptr.left == null)   return (Math.Abs(ptr.data - ptr.right.data) == 1) &&   treeContinuous(ptr.right);   // If right subtree is empty then only check left   if (ptr.right == null)   return (Math.Abs(ptr.data - ptr.left.data) == 1) &&   treeContinuous(ptr.left);   // If both left and right subtrees are not empty check   // everything   return Math.Abs(ptr.data - ptr.left.data)==1 &&   Math.Abs(ptr.data - ptr.right.data)==1 &&   treeContinuous(ptr.left) &&   treeContinuous(ptr.right);  }  /* Driver program to test mirror() */ static public void Main(String []args)  {   Node root = newNode(3);   root.left = newNode(2);   root.right = newNode(4);   root.left.left = newNode(1);   root.left.right = newNode(3);   root.right.right = newNode(5);   if(treeContinuous(root))   Console.WriteLine( 'Yes') ;   else  Console.WriteLine( 'No');  }  }  //contributed by Arnab Kundu  
JavaScript
<script> // JavaScript program to check if a tree is continuous or not  /* A binary tree node has data pointer to left child  and a pointer to right child */ class Node  {   constructor()  {  this.data=0;  this.left = null;  this.right = null;  } };  /* Helper function that allocates a new node with the  given data and null left and right pointers. */ function newNode(data)  {   var node = new Node();   node.data = data;   node.left = node.right = null;   return(node);  }  // Function to check tree is continuous or not  function treeContinuous( ptr)  {   // if next node is empty then return true   if (ptr == null)   return true;   // if current node is leaf node then return true   // because it is end of root to leaf path   if (ptr.left == null && ptr.right == null)   return true;   // If left subtree is empty then only check right   if (ptr.left == null)   return (Math.abs(ptr.data - ptr.right.data) == 1) &&   treeContinuous(ptr.right);   // If right subtree is empty then only check left   if (ptr.right == null)   return (Math.abs(ptr.data - ptr.left.data) == 1) &&   treeContinuous(ptr.left);   // If both left and right subtrees are not empty check   // everything   return Math.abs(ptr.data - ptr.left.data)==1 &&   Math.abs(ptr.data - ptr.right.data)==1 &&   treeContinuous(ptr.left) &&   treeContinuous(ptr.right);  }  /* Driver program to test mirror() */ var root = newNode(3);  root.left = newNode(2);  root.right = newNode(4);  root.left.left = newNode(1);  root.left.right = newNode(3);  root.right.right = newNode(5);  if(treeContinuous(root))   document.write( 'Yes') ;  else  document.write( 'No');  </script> 

산출
Yes

또 다른 접근 방식(BFS(Queue) 사용)

설명: 우리는 단순히 각 노드 레벨을 레벨별로 순회하고 상위 노드와 하위 노드의 차이가 1인지 확인한 다음 모든 노드에 대해 true인 경우 반환합니다. 진실 그렇지 않으면 우리는 돌아올 것이다 거짓 .

자바테이블

구현:

C++14
// CPP Code to check if the tree is continuous or not #include    using namespace std; // Node structure struct node {  int val;  node* left;  node* right;  node()  : val(0)   left(nullptr)   right(nullptr)  {  }  node(int x)  : val(x)   left(nullptr)   right(nullptr)  {  }  node(int x node* left node* right)  : val(x)   left(left)   right(right)  {  } }; // Function to check if the tree is continuous or not bool continuous(struct node* root) {  // If root is Null then tree isn't Continuous  if (root == NULL)  return false;  int flag = 1;  queue<struct node*> Q;  Q.push(root);  node* temp;  // BFS Traversal  while (!Q.empty()) {  temp = Q.front();  Q.pop();  // Move to left child  if (temp->left) {  // if difference between parent and child is  // equal to 1 then do continue otherwise make  // flag = 0 and break  if (abs(temp->left->val - temp->val) == 1)  Q.push(temp->left);  else {  flag = 0;  break;  }  }  // Move to right child  if (temp->right) {  // if difference between parent and child is  // equal to 1 then do continue otherwise make  // flag = 0 and break  if (abs(temp->right->val - temp->val) == 1)  Q.push(temp->right);  else {  flag = 0;  break;  }  }  }  if (flag)  return true;  else  return false; } // Driver Code int main() {  // Constructing the Tree  struct node* root = new node(3);  root->left = new node(2);  root->right = new node(4);  root->left->left = new node(1);  root->left->right = new node(3);  root->right->right = new node(5);  // Function Call  if (continuous(root))  cout << 'Truen';  else  cout << 'Falsen';  return 0; } // This code is contributed by Sanjeev Yadav. 
Java
// JAVA Code to check if the tree is continuous or not import java.util.*; class GFG { // Node structure static class node {  int val;  node left;  node right;  node()  {  this.val = 0;  this.left = null;  this.right= null;    }  node(int x)  {  this.val = x;  this.left = null;  this.right= null;    }  node(int x node left node right)  {  this.val = x;  this.left = left;  this.right= right;   } }; // Function to check if the tree is continuous or not static boolean continuous(node root) {  // If root is Null then tree isn't Continuous  if (root == null)  return false;  int flag = 1;  Queue<node> Q = new LinkedList<>();  Q.add(root);  node temp;  // BFS Traversal  while (!Q.isEmpty())  {  temp = Q.peek();  Q.remove();  // Move to left child  if (temp.left != null)  {  // if difference between parent and child is  // equal to 1 then do continue otherwise make  // flag = 0 and break  if (Math.abs(temp.left.val - temp.val) == 1)  Q.add(temp.left);  else  {  flag = 0;  break;  }  }  // Move to right child  if (temp.right != null)   {  // if difference between parent and child is  // equal to 1 then do continue otherwise make  // flag = 0 and break  if (Math.abs(temp.right.val - temp.val) == 1)  Q.add(temp.right);  else   {  flag = 0;  break;  }  }  }  if (flag != 0)  return true;  else  return false; } // Driver Code public static void main(String[] args) {    // Constructing the Tree  node root = new node(3);  root.left = new node(2);  root.right = new node(4);  root.left.left = new node(1);  root.left.right = new node(3);  root.right.right = new node(5);  // Function Call  if (continuous(root))  System.out.print('Truen');  else  System.out.print('Falsen'); } } // This code is contributed by Rajput-Ji 
Python3
# Python program for the above approach # Node structure class Node: def __init__(self x): self.val = x self.left = None self.right = None # Function to check if the tree is continuous or not def continuous(root): # If root is None then tree isn't Continuous if root is None: return False flag = 1 Q = [] Q.append(root) temp = None # BFS Traversal while len(Q) != 0: temp = Q.pop(0) # Move to left child if temp.left is not None: # if difference between parent and child is # equal to 1 then do continue otherwise make # flag = 0 and break if abs(temp.left.val - temp.val) == 1: Q.append(temp.left) else: flag = 0 break # Move to right child if temp.right is not None: # if difference between parent and child is # equal to 1 then do continue otherwise make # flag = 0 and break if abs(temp.right.val - temp.val) == 1: Q.append(temp.right) else: flag = 0 break if flag != 0: return True else: return False # Driver Code # Constructing the Tree root = Node(3) root.left = Node(2) root.right = Node(4) root.left.left = Node(1) root.left.right = Node(3) root.right.right = Node(5) # Function Call if continuous(root): print('True') else: print('False') # This code is contributed by codebraxnzt 
C#
// C# Code to check if the tree is continuous or not using System; using System.Collections.Generic; class GFG {  // Node structure  public  class node  {  public  int val;  public  node left;  public  node right;  public node()  {  this.val = 0;  this.left = null;  this.right = null;   }  public node(int x)  {  this.val = x;  this.left = null;  this.right = null;  }  public node(int x node left node right)  {  this.val = x;  this.left = left;  this.right = right;   }  };  // Function to check if the tree is continuous or not  static bool continuous(node root)  {  // If root is Null then tree isn't Continuous  if (root == null)  return false;  int flag = 1;  Queue<node> Q = new Queue<node>();  Q.Enqueue(root);  node temp;  // BFS Traversal  while (Q.Count != 0)  {  temp = Q.Peek();  Q.Dequeue();  // Move to left child  if (temp.left != null)  {  // if difference between parent and child is  // equal to 1 then do continue otherwise make  // flag = 0 and break  if (Math.Abs(temp.left.val - temp.val) == 1)  Q.Enqueue(temp.left);  else  {  flag = 0;  break;  }  }  // Move to right child  if (temp.right != null)   {  // if difference between parent and child is  // equal to 1 then do continue otherwise make  // flag = 0 and break  if (Math.Abs(temp.right.val - temp.val) == 1)  Q.Enqueue(temp.right);  else   {  flag = 0;  break;  }  }  }  if (flag != 0)  return true;  else  return false;  }  // Driver Code  public static void Main(String[] args)  {  // Constructing the Tree  node root = new node(3);  root.left = new node(2);  root.right = new node(4);  root.left.left = new node(1);  root.left.right = new node(3);  root.right.right = new node(5);  // Function Call  if (continuous(root))  Console.Write('Truen');  else  Console.Write('Falsen');  } } // This code is contributed by Rajput-Ji  
JavaScript
<script> // Javascript Code to check if the tree is continuous or not // Node structure class Node {   constructor(x)  {  this.val = x;  this.left = null;  this.right= null;  } } // Function to check if the tree is continuous or not function continuous(root) {  // If root is Null then tree isn't Continuous  if (root == null)  return false;    let flag = 1;  let Q = [];  Q.push(root);  let temp;    // BFS Traversal  while (Q.length!=0)  {  temp = Q.shift();      // Move to left child  if (temp.left != null)  {    // if difference between parent and child is  // equal to 1 then do continue otherwise make  // flag = 0 and break  if (Math.abs(temp.left.val - temp.val) == 1)  Q.push(temp.left);  else  {  flag = 0;  break;  }  }    // Move to right child  if (temp.right != null)  {    // if difference between parent and child is  // equal to 1 then do continue otherwise make  // flag = 0 and break  if (Math.abs(temp.right.val - temp.val) == 1)  Q.push(temp.right);  else   {  flag = 0;  break;  }  }  }  if (flag != 0)  return true;  else  return false; } // Driver Code // Constructing the Tree let root = new Node(3); root.left = new Node(2); root.right = new Node(4); root.left.left = new Node(1); root.left.right = new Node(3); root.right.right = new Node(5); // Function Call if (continuous(root))  document.write('True  
'
); else document.write('False
'
); // This code is contributed by avanitrachhadiya2155 </script>

산출
True

시간 복잡도: O(n)

보조 공간: O(N) 여기 N은 트리의 노드 수입니다.

퀴즈 만들기