-1

Will this code work to find the rightmost leaf recursively. Thank you

 Node* findRightMostLeaf(Node* curNode){
 if (curNode== NULL) 
     return null;
 if (curNode->rchild!= NULL)
   return findRightMostLeaf(curNode->rchild);
 if (curNode->lchild!= NULL)
   return findRightMostLeaf(curNode->lchild);
else return curNode; } 
David
  • 27
  • 3
  • 1
    I suggest you draw a small tree on a piece of paper and start from the root node (or any other node), see where this code takes you, it's not long and you can follow it. – SA.93 Dec 03 '20 at 08:18
  • Why don't you just try it since you have already written the function? If it does not what you expect, please provide a minimum working example. – StefanKssmr Dec 03 '20 at 08:18
  • No, this code will not work. Even if you provide a definition of `Node`, `curNode` is a pointer, so you have to use `->` instead of `.` and `null` is undefined. – mch Dec 03 '20 at 08:21
  • I did draw it before I wrote this function but since I am new at recursion, I am trying to make sure is right and if not some suggestion where did I go wrong – David Dec 03 '20 at 08:23
  • what is leaf in your model? is it different from a node? – Will Ness Dec 03 '20 at 08:26
  • `if (curNode->lchild!= NULL) \\ return findRightMostLeaf(curNode->lchild);` This loooks suspicious. Why going here to the left? You may detail what you call *the rightmost leaf* – Damien Dec 03 '20 at 08:29
  • Leaf is the node with no children so I am looking for the rightmost node that does not have children – David Dec 03 '20 at 08:33
  • looks like it should do the work then. – Will Ness Dec 03 '20 at 14:38

1 Answers1

-1

Let assume your constructed tree is a binary search tree. In that case, your provide solution should be worked. You can check other iterative solution here https://www.geeksforgeeks.org/deepest-right-leaf-node-binary-tree-iterative-approach/

  • 1
    The example on that website starts with `#include / using namespace std;`. [Why should I not `#include `?](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) [Why is `using namespace std;` considered bad practice?](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) To those who learn C++ I would recommend to avoid this website - it teaches how to write bad code and has nothing to do with professional programming. – Evg Dec 03 '20 at 08:50
  • Actually my main focused on providing a simple alternative algorithm example that is easy to visible and understands. – Md Abul Kashem Dec 03 '20 at 09:48
  • The rules of SO suggest to write self-contained answers. Answers that just include external links without explanations are not very useful. When links die, they become completely useless. – Evg Dec 03 '20 at 09:52