假设我在树中有一个节点,我怎样才能获得其祖先是这个节点的所有叶子节点?我已经像这样定义了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;
}
}
答案 0 :(得分:10)
使用递归。
像这样(未经测试):
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;
}
答案 1 :(得分:0)
创建一个堆栈并推送根节点。
import React from "react";
import { BrowserRouter } from 'react-router-dom';
import { MDBNav, MDBNavItem, MDBNavLink } from "mdbreact";
const MiTabs = props => {
return (
<BrowserRouter>
<MDBNav className="nav-tabs mt-5">
{props.data.map(a => (
<MDBNavItem>
//Add a link prop to component below
<MDBNavLink link active='true' to={a.enlace}>
{a.nombre}
</MDBNavLink>
</MDBNavItem>
))}
<MDBNavItem>
//Add a link prop to component below
<MDBNavLink link active to="#!">Active</MDBNavLink>
</MDBNavItem>
<MDBNavItem>
//Add a link prop to component below
<MDBNavLink link to="#!">NO Active</MDBNavLink>
</MDBNavItem>
</MDBNav>
</BrowserRouter>
);
};
export default MiTabs;
调用递归方法。
public static void main(String[] args) {
// System.out.println("Enter a number to changeit at char ");
Random random = new Random();
int x = random.nextInt(26)+65; //0 to 25
System.out.println((char)x);
}