按照层序遍历创建树
public void initTree (int[] tree)
{
Queue queue = new Queue();
TreeNode root = new TreeNode(tree[0]);
queue.Enqueue(root);
for (int i = 1; i < tree.Length; i++)
{
TreeNode currentNode = (TreeNode)queue.Peek();
if (currentNode.left == null)
{
currentNode.left = new TreeNode(tree[i]);
continue;
}
if (currentNode.right == null)
{
currentNode.right = new TreeNode(tree[i]);
}
if (currentNode.left!=null && currentNode.right!=null)
{
queue.Dequeue();
queue.Enqueue(currentNode.left);
queue.Enqueue(currentNode.right);
}
}
}
网友评论