二叉树的递归广度优先遍历

时间:2014-01-17 19:54:00

标签: data-structures binary-tree breadth-first-search tree-traversal

我正在尝试使用C或C ++语言中的递归来找到实现二叉树遍历的方法。

我可以使用队列或smth通过迭代算法实现先呼吸遍历(读取每个级别)。否则,但我需要一个算法用递归来做这个。

问题是:    对于级别(从0开始)和节点信息的每个级别打印索引。

实施例:    0级:A    1级:B C

由于

4 个答案:

答案 0 :(得分:0)

以下是示例代码

/* Function to print level order traversal a tree*/
void printLevelOrder(struct node* root)
{
  int h = height(root);
  int i;
  for(i=1; i<=h; i++)
    printGivenLevel(root, i);
}     

/* Print nodes at a given level */
void printGivenLevel(struct node* root, int level)
{
  if(root == NULL)
     return;
  if(level == 1)
    printf("%d ", root->data);
  else if (level > 1)
  {
    printGivenLevel(root->left, level-1);
    printGivenLevel(root->right, level-1);
  }
}

此处提供解决方案 http://www.geeksforgeeks.org/level-order-tree-traversal/

答案 1 :(得分:0)

这是一个JavaScript实现,它伪造了你要求的广度优先遍历的输出,但是使用Depth First递归。我将节点值存储在数组内的每个深度处,在散列内部。如果某个级别已存在(我们发生了冲突),那么我们只需按该级别的数组即可。您可以使用数组而不是JavaScript对象,因为我们的级别是数字,可以作为数组索引。您可以返回节点,值,转换为链接列表或任何您想要的。我只是为了简单起见而返回值。

BinarySearchTree.prototype.breadthFirstRec = function() {

    var levels = {};

    var traverse = function(current, depth) {
        if (!current) return null;
        if (!levels[depth]) levels[depth] = [current.value];
        else levels[depth].push(current.value);
        traverse(current.left, depth + 1);
        traverse(current.right, depth + 1);
    };

    traverse(this.root, 0);
    return levels;
};


var bst = new BinarySearchTree();
bst.add(20, 22, 8, 4, 12, 10, 14, 24);
console.log('Recursive Breadth First: ', bst.breadthFirstRec());
/*Recursive Breadth First:  
{ '0': [ 20 ],
  '1': [ 8, 22 ],
  '2': [ 4, 12, 24 ],
  '3': [ 10, 14 ] } */

以下是在JavaScript中使用迭代方法的实际广度优先遍历的示例,以防任何人感兴趣。 JavaScript规则!

BinarySearchTree.prototype.breadthFirst = function() {

    var result = '',
        queue = [],
        current = this.root;

    if (!current) return null;
    queue.push(current);

    while (current = queue.shift()) {
        result += current.value + ' ';
        current.left && queue.push(current.left);
        current.right && queue.push(current.right);
    }
    return result;
};

console.log('Breadth First: ', bst.breadthFirst());
//Breadth First:  20 8 22 4 12 24 10 14

答案 2 :(得分:0)

我是这样实现的。仅针对基本条件进行了测试,未完全测试。

public class Node {

int data;
Node left, right;

Node(int data){
    this.data = data;
}

/**
 * Searches through the tree for appropiate position of the value to be inserted and inserts it.
 * @param data
 */
public void insert(int newValue) {
    if(newValue < data) {
        if(left == null) {
            left = new Node(newValue);
        }else {
            left.insert(newValue);
        }
    }else {
        if(right == null) {
            right = new Node(newValue);
        }else {
            right.insert(newValue);
        }
    }
}

public void bfs(boolean isStartingLevel) {
    if(isStartingLevel) {
        System.out.println(data);
    }
    if(left != null) {
        System.out.println(left.data);
    } 
    if(right != null) {
        System.out.println(right.data);
    } 
    if(left != null) {
        left.bfs(false);
    }
    if(right != null) {
        right.bfs(false);
    }
}

public static void main(String[] args) {
    Node n1 = new Node(7);
    Node n2 = n1;
    n1.insert(9); // right of 7
    n1.insert(4); // left of 7
    //n1.insert(3); // left of 4
    n1.insert(5); // right of 4
    //n1.insert(10); // right of 9
    n1.insert(8); // left of 9

    n2.bfs(true);


}

}

答案 3 :(得分:0)

class Solution {
 public List<List<Integer>> levelOrder(TreeNode root) {
    List<List<Integer>> list=new ArrayList<>();
    traverse(root,list,0);
    return list;
}

void traverse(TreeNode root, List<List<Integer>> list,int level)
{
    if(root==null)    //if root is null return 
        return;

    if(list.size()<(level+1))
        list.add(new ArrayList<>());

    list.get(level).add(root.val);

    traverse(root.left,list,level+1);

    traverse(root.right,list,level+1);
}
}

/*    Input- [3,9,20,null,null,15,7]  */
/*    Output [[3],[9,20],[15,7]]     */