繁体   English   中英

如何获取树的所有叶节点?

[英]How to get all leaf nodes of a tree?

假设我在树中有一个节点,如何获取其祖先是该节点的所有叶节点? 我已经像这样定义了 TreeNode:

public class TreeNode<T>
{
    /** all children of the node */
    private List<TreeNode<T>> children = new ArrayList<TreeNode<T>>();
    /** the parent of the node, if the node is root, parent = null */
    private TreeNode<T> parent = null;
    /** the stored data of the node */
    private T data = null;

    /** the method I want to implement */
    public Set<TreeNode<T>> getAllLeafNodes()
    {
        Set<TreeNode<T>> leafNodes = new HashSet<TreeNode<T>>();
        return leafNodes;
    }
}

使用递归。

  • 如果节点本身是叶子,则返回它
  • 否则,返回其子节点的所有叶节点

像这样的东西(未测试):

public Set<TreeNode<T>> getAllLeafNodes() {
    Set<TreeNode<T>> leafNodes = new HashSet<TreeNode<T>>();
    if (this.children.isEmpty()) {
        leafNodes.add(this);
    } else {
        for (TreeNode<T> child : this.children) {
            leafNodes.addAll(child.getAllLeafNodes());
        }
    }
    return leafNodes;
}

创建堆栈并推送根节点。

Stack<Node> st = new Stack<>();
st.push(root);      
CL(st.peek());

调用递归方法。

public void CL(Node root){
        if (st.peek().left == null && st.peek().right == null ) {//if leaf node
            System.out.println(st.peek().data);//print
            st.pop();
            return;
        }
        else{
            if(st.peek().left != null){
                st.add(st.peek().left);
                CL(st.peek());
            }
            if(st.peek().right != null){
                st.add(st.peek().right);
                CL(st.peek());
            }
        }
        st.pop();
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM