【问题标题】:Recursive breadth-first traversal of binary tree二叉树的递归广度优先遍历
【发布时间】:2014-01-17 19:54:00
【问题描述】:

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

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

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

示例: 0级:A 1级:B C

谢谢

【问题讨论】:

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


【解决方案1】:

这里是示例代码

/* 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/

【讨论】:

  • 这更像是一个 IDDFS 而不是 BFS。
【解决方案2】:

这是一个 JavaScript 实现,它伪造了您要求的广度优先遍历的输出,但使用深度优先递归。我将每个深度的节点值存储在一个数组内,一个哈希值内。如果一个级别已经存在(我们有碰撞),那么我们只需推送到该级别的数组。您也可以使用数组而不是 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

【讨论】:

    【解决方案3】:

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

    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);
    
    
    }
    
    }
    

    【讨论】:

      【解决方案4】:
      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]]     */
      

      【讨论】:

        猜你喜欢
        • 2019-01-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多