zoukankan      html  css  js  c++  java
  • 从上往下打印出二叉树的每个节点,同层节点从左至右打印

    // test20.cpp : 定义控制台应用程序的入口点。
    //

    #include "stdafx.h"
    #include<iostream>
    #include<vector>
    #include<string>
    #include<queue>
    #include<stack>
    
    using namespace std;
    
    
    
    struct TreeNode {
    	int val;
    	struct TreeNode *left;
    	struct TreeNode *right;
    	TreeNode(int x) :
    	val(x), left(NULL), right(NULL) {
    	}
    };
    class Solution {
    public:
    	vector<int> PrintFromTopToBottom(TreeNode *root) {
    		vector<int> vec;
    		queue<TreeNode* > qu;
    		if (root == NULL)return vec;
    		qu.push(root);
    		while (!qu.empty())
    		{
    			//cout << qu.front()->val << "  ";
    			vec.push_back(qu.front()->val);
    			if (qu.front()->left != NULL) qu.push(qu.front()->left);
    			if (qu.front()->right != NULL) qu.push(qu.front()->right);
    			qu.pop();
    		}
    		return vec;
    	}
    
    
    	void preCreate(TreeNode* &T)
    	{
    		int num;
    		cin >> num;
    		if (num == 0) T = NULL;
    		else
    		{
    			T = new TreeNode(num);
    			preCreate(T->left);
    			preCreate(T->right);
    		}
    	}
    
    	void preOrder(TreeNode* T)
    	{
    		if (T == NULL) return; 
    		else
    		{
    			cout << T->val << "  ";
    			preOrder(T->left);
    			preOrder(T->right);
    		}
    	}
    };
    int main()
    {
    	
    	Solution so;
    	TreeNode *T1;
    	TreeNode *T2;
    	vector<int> vec;
    
    	cout << "创建T1:" << endl;
    	so.preCreate(T1);
    	cout << "创建T1成功!" << endl;
    
    
    
    	cout << "T1的前序遍历:" << endl;
    	so.preOrder(T1);
    	cout << endl;
    
    	vec = so.PrintFromTopToBottom(T1);
    
    	cout << "层次遍历的结果是:" << endl;
    	for (auto it = vec.begin();it != vec.end();it++)
    		cout << *it << "  ";
    
    
    	
    	
    	cout << endl;
    	return 0;
    }
  • 相关阅读:
    prometheus基础概念
    Prometheus告警处理
    什么是prometheus?
    Prometheus的PromQL
    Prometheus的Exporter详解
    leetcode unique path I&&II
    leetcode Palindrome Partitioning
    leetcode 最大子矩阵(5星推荐)
    leetcode Sum Root to Leaf Numbers 二叉树所有叶节点的路径和
    leetcode Spiral Matrix I
  • 原文地址:https://www.cnblogs.com/wdan2016/p/5991142.html
Copyright © 2011-2022 走看看