【发布时间】:2016-02-29 23:56:33
【问题描述】:
我正在学习实现二叉树,我正在尝试获取每个节点的级别,我尝试从根节点遍历到叶节点,但无法获得正确的答案。这是我的代码
public class BinaryTree
{
private Node root;
/**
Constructs an empty tree.
*/
public BinaryTree() {
root=new Node();
root = null; }
/**
Constructs a tree with one node and no children.
@param rootData the data for the root
*/
public BinaryTree(Object rootData)
{ root=new Node();
root.data=rootData;
}
/**
Constructs a binary tree.
@param rootData the data for the root
@param left the left subtree
@param right the right subtree
*/
public BinaryTree(Object rootData, BinaryTree left, BinaryTree right)
{
root = new Node();
root.data = rootData;
root.left = left.root;
root.right = right.root;
}
class Node
{
public Object data;
public Node left;
public Node right;
public String printTree(int level)
{
return null;
}
}
int getLevelUtil(Node n, Object data, int level)
{
if (n == null)
return 0;
if (n.data == data)
return level;
int downlevel = getLevelUtil(n.left, data, level+1);
if (downlevel != 0)
return downlevel;
downlevel = getLevelUtil(n.right, data, level+1);
return downlevel;
}
/* Returns level of given data value */
int getLevel(Node n, int data)
{
return getLevelUtil(n,data,1);
}
/**
Returns the height of the subtree whose root is the given node.
@param n a node or null
@return the height of the subtree, or 0 if n is null
*/
private static int height(Node n)
{
if (n == null) { return 0; }
else { return 1 + Math.max(height(n.left), height(n.right)); }
}
/**
Returns the height of this tree.
@return the height
*/
public Object data()
{
return root.data;
}
/**
Gets the left subtree of this tree
@return the left child of the root
*/
public BinaryTree left()
{
return null;
}
/**
Gets the right subtree of this tree
@return the right child of the root
*/
public BinaryTree right()
{
return null;
}
/**
* Sets a new right child
* @param child the new right child
*/
public void setRight(BinaryTree child)
{
root.right=child.root;
}
/**
* Sets a new left child
* @param child the new left child
*/
public void setLeft(BinaryTree child)
{
root.left=child.root;
}
public void setData(Object data)
{
root.data=data;
}
public boolean isLeaf()
{
if(root.left==null&& root.right==null)
return true;
else
return false;
}
public String printTree()
{
String s=new String();
s= s+printTree(root);
return s;
}
public String printTree(Node parent)
{ String s=new String();
if (parent == null) { return ""+" "; }
s=s+parent.data+"(level:"+(height(parent))+")";
s=s+printTree(parent.left);
s=s+ printTree(parent.right);
return(s);
}
}
我可以通过什么方式做到这一点...???
【问题讨论】:
-
您看到的错误是什么?顺便说一句,我认为你的构造函数中有一个空树错误,你创建了一个新的
Node然后将root设置为 null。 -
我不知道我应该如何实现一个函数,以便我可以获得这棵树中每个节点的级别
-
检查我的解决方案。每个节点都有左节点、右节点和父节点。
标签: java tree binary-tree