从二叉树中删除叶子

编程入门 行业动态 更新时间:2024-10-22 14:32:35
本文介绍了从二叉树中删除叶子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 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.

推荐答案

您的if语句有点混乱;仅会使用一个分支.想一想如果高度值p.left或p.right为null会发生什么情况.

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.

更多推荐

从二叉树中删除叶子

本文发布于:2023-11-30 04:14:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1648681.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:叶子   二叉树

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!