Advertisement
satishfrontenddev5

Untitled

Feb 22nd, 2024
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. Write an algorithm to find the "next" node (i.e., in-order successor) of a given node in a binary search tree. You may assume that each parent has a link to its child.
  2.  
  3. Input format
  4. The tree will be given along with the node for which you have to find the successor.
  5.  
  6. Q: Q number of queries will be given to you.
  7.  
  8. Output format
  9. Print the value of the successor node. If it doesn’t exist then print -1.
  10.  
  11. Sample Input 1
  12. 3
  13.  
  14. 5 4 6
  15.  
  16. 0 1 2
  17.  
  18. 1 -1 -1
  19.  
  20. 2 -1 -1
  21.  
  22. 2
  23.  
  24. 2
  25.  
  26. 0
  27.  
  28. Sample Output 1
  29. -1
  30.  
  31. 6
  32.  
  33. Explanation 1
  34. The tree given in the sample will look like -
  35.  
  36. image
  37.  
  38. There will be no successor of node with value 6.
  39.  
  40. The successor of node having value 5 will be the node with value 6.
  41.  
  42. Constraints
  43. 1<= Number of nodes <= 20000
  44.  
  45. 1<= Q <= 10000
  46.  
  47. /*
  48. Definition for TreeNode
  49. class TreeNode {
  50.     constructor(val) {
  51.         this.val = val;
  52.         this.left = null;
  53.         this.right = null;
  54.         this.next =null;
  55.     }
  56. }
  57. */
  58.  
  59. function getInorderTraversal(root,nodes){
  60.     if(root==null) return ;
  61.     getInorderTraversal(root.left,nodes);
  62.     nodes.push(root);
  63.     getInorderTraversal(root.right,nodes);
  64. }
  65. /**
  66.  * @param {TreeNode} root
  67.  * @param {TreeNode} givenNode
  68.  * @return {TreeNode}
  69.  */
  70. function inOrderSuccessor(root, givenNode) {
  71.     let nodes=[];
  72.     getInorderTraversal(root,nodes);
  73.     let nextInorderSuccessor=null;
  74.     nodes.map((node,index)=>{
  75.         if(node==givenNode&&index+1<nodes.length){
  76.             nextInorderSuccessor=nodes[index+1];
  77.         }
  78.  
  79.     })
  80.     return nextInorderSuccessor;
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement