zoukankan      html  css  js  c++  java
  • 二叉树的层序遍历

      输出不太对,只考虑了完全二叉树的情况。。。

      代码:

    #include <iostream>
    #include <queue>
    #include <vector>
    #include <math.h>
     
    typedef struct BaseNode* tree;
     
    struct BaseNode {
    	int val;
    	BaseNode* left;
    	BaseNode* right;
    
    	BaseNode() {};
    	BaseNode(int v) : val(v), left(nullptr), right(nullptr)
    	{
    	}
    };
     
    void insert(tree & root, int & v)
    {
    	std::cin >> v;
    	if (v == 0)
    		root = nullptr;
    	else
    	{
    		root = new BaseNode(v);
    		insert(root->left, v);
    		insert(root->right, v);
    	}
    }
     
    void sequence(tree root)
    {
    	std::queue<tree> nodes;
    	std::vector<int> nums;
    	tree rptr = root;
    
    	nodes.push(rptr);
    	while (!nodes.empty())
    	{
    		rptr = nodes.front();
    		nodes.pop();
     
    		if (rptr)
    		{
    			nums.push_back(rptr->val);
    			nodes.push(rptr->left);
    			nodes.push(rptr->right);
    		}
    	}
    
    	for (int i = 0; i < int(log(nums.size() + 1)); i++)
    	{
    		for (int j = 0; j < nums.size() - i; j++)
    			std::cout << " ";
    		for (int j = (i < 2 ? i : i + 1); j <= 2 * i; j++)
    			std::cout << nums[j] << " ";
    		std::cout << std::endl;
    	}
    
    }
     
     
    int main()
    {
    	tree root;
    	int v;
    
    	insert(root, v);
    	sequence(root);
    
    	return 0;
    }
    

      

      

      

      

  • 相关阅读:
    ES6新特性
    CSS Sprites (css精灵)
    标准盒子模型和IE盒子模型
    鼠标跟随运动效果
    git 命令大全
    JavaScript 原型链
    js基础---cookie存储
    html5新增标签
    css清除浮动的方法
    querySelectorAll与getElementsBy对比有什么不同
  • 原文地址:https://www.cnblogs.com/darkchii/p/9001767.html
Copyright © 2011-2022 走看看