Deleting leaves from a binary tree

一曲冷凌霜 提交于 2019-12-11 08:52:11

问题


public void deleteLeaves(BSTNode<T> p){                     //deletes leaves
    if(p.left != null){
      if(isLeaf(p.left))
        p.left = null;
    }
    else if(p.right != null){
      if(isLeaf(p.right))
        p.right = null;
    }
    else{
      deleteLeaves(p.right);
      deleteLeaves(p.left); 
    }
  }

I cannot seem to figure out as to why it is not correctly deleting the leaves. It seems to only delete the final leaf of the tree. Any advice that helps would greatly be appreciated.


回答1:


Your if-statements are a bit messed up; Only one of the branches will be taken. Think about what should happen if neighter p.left nor p.right is null.

If I understand your data structure correctly, I'd probably write it like this:

// If there is something to the left...
if (p.left != null)
    if (isLeaf(p.left))
        p.left = null;             // delete it if it's a leaf...
    else
        deleteLeaves(p.left);      // else recurse.

// If there's something to the right...
if (p.right != null)
    if (isLeaf(p.right))
        p.right = null;            // delete it if it's a leaf...
    else
        deleteLeaves(p.right);     // else recurse.



回答2:


At the moment, if p.left != null then it won't even check for p.right. The else-if should just be an if. Also, you're saying if both neighboring nodes are null, then call deleteLeaves() on them, which makes no sense cuz they're null. Restructure your code; @aioobe has a good suggestion




回答3:


To use recursion properly, it must be in the same kind of control statement. You shouldn't check the condition in an if, and then do the actual recursion in an else if or else.



来源:https://stackoverflow.com/questions/7839664/deleting-leaves-from-a-binary-tree

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!