【发布时间】:2013-07-29 23:23:06
【问题描述】:
我的问题是用签名写一个方法
public static BinaryTree generate(BinaryTree root)
(可以添加其他参数)
这个方法必须返回一个BinaryTree,就像给定的参数一样(同样大小等等),它只需要改变它的节点中的值。当我们在root 上使用前序遍历时,结果树的每个节点的值必须等于处理等效节点的位置。我们从 1 开始计数。
public class BinaryTree {
public int value;
public BinaryTree left;
public BinaryTree right;
public BinaryTree(int value, BinaryTree left, BinaryTree right)
{
this.value = value;
this.left = left;
this.right = right;
}
}
我尝试了以下方法,但无法正常工作。
public static BinaryTree preOrder(BinaryTree root, int num)
{
//We ALWAYS give 1 as num value!!
if (root == null)
return null;
root.value = num;
preOrder(root.left, ++num);
preOrder(root.right, ++num);
return root;
}
例如,如果我们有一个二叉树:
3
/ \
2 1
/ \
1 0
(节点中有什么值并不重要!)
我们的方法必须返回这棵树:
1
/ \
2 5
/ \
3 4
【问题讨论】:
标签: java binary-tree preorder