|
| 1 | +// Following is the given Tree node structure. |
| 2 | +/************** |
| 3 | +class TreeNode { |
| 4 | + TreeNode<T>** children; |
| 5 | + int childCount; |
| 6 | + |
| 7 | + public: |
| 8 | + T data; |
| 9 | + |
| 10 | + TreeNode(T data); // Constructor |
| 11 | + int numChildren(); |
| 12 | + void addChild(TreeNode<T>* child); |
| 13 | + TreeNode<T>* getChild(int index); |
| 14 | + void setChild(int index, TreeNode<T>* child); |
| 15 | + void removeChild(int index); |
| 16 | + |
| 17 | +}; |
| 18 | +***************/ |
| 19 | + |
| 20 | +TreeNode<int>* removeLeafNodes(TreeNode<int>* root) { |
| 21 | + if(root==NULL){ |
| 22 | + return NULL; |
| 23 | + } |
| 24 | + if(root->numChildren()==0){ |
| 25 | + delete root; |
| 26 | + return NULL; |
| 27 | + } |
| 28 | + for(int i=0;i<root->numChildren();i++){ |
| 29 | + TreeNode<int>* child=root->getChild(i); |
| 30 | + if(child->numChildren()==0){ |
| 31 | + delete child; |
| 32 | + root->removeChild(i); |
| 33 | + i--; |
| 34 | + } |
| 35 | + |
| 36 | + } |
| 37 | + for(int i=0;i<root->numChildren();i++){ |
| 38 | + removeLeafNodes(root->getChild(i)); |
| 39 | + |
| 40 | + } |
| 41 | + return root; |
| 42 | +} |
| 43 | + |
0 commit comments