• [LeetCode] Binary Tree Level Order Traversal 2


    Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).

    For example: Given binary tree {3,9,20,#,#,15,7},

        3
       / 
      9  20
        /  
       15   7
    

     

    return its bottom-up level order traversal as:

    [
      [15,7]
      [9,20],
      [3],
    ]

    head.h里代码实现如下:
    #include<vector>
    #include<queue>
    using namespace std;
    #define NULL 0
    
    struct TreeNode
    {
    	int val;
    	TreeNode *left;
    	TreeNode *right;
    	TreeNode(int x):val(x),left(NULL),right(NULL) {}
    };
    
    struct Node
    {
    	TreeNode *node;
    	int level;
    	Node(){}
    	Node(TreeNode *n,int l):node(n),level(l){}
    };
    
    class Solution
    {
    private:
    	vector<vector<int> > ret;
    	vector<vector<int> > retReverse;
    public:
    	vector<vector<int> > leverOrder(TreeNode *root)
    	{
    		ret.clear();
    
    		if(root == NULL)
    			return ret;
    
    		queue<Node> q;
    		q.push (Node(root,0));
    
    		vector<int> a;
    		int curLever = -1;
    
    		while(!q.empty() )
    		{
    			Node node = q.front();
    			if(node.node->left)
    				q.push(Node(node.node->left,node.level+1));
    			if(node.node->right)
    				q.push(Node(node.node->right,node.level+1));
    
    			if(curLever != node.level)
    			{
    				if(curLever != -1)
    					ret.push_back(a);
    				curLever = node.level ;
    				a.clear();
    				a.push_back(node.node->val);
    			}
    			else
    				a.push_back(node.node->val);
    			
    			q.pop();
    		}
    
    		ret.push_back(a);
    
    		retReverse.clear();
    
    		for(int i=ret.size()-1;i>=0;i--)
    			retReverse.push_back(ret[i]);
    
    		return retReverse;
    
    	}
    };
    

     main.cpp里代码实现如下:

    #include"head.h"
    #include<iostream>
    
    int main()
    {
     TreeNode *root;
     root=new TreeNode(3);
     root->left = new TreeNode(9);
     root->right =  new TreeNode(20);
     root->right->left =  new TreeNode(15);
     root->right->right =  new TreeNode(7);
     Solution sol;
     for(vector<vector<int> >::size_type ix=0;ix!=sol.leverOrder(root).size();++ix)
      {for(vector<int>::size_type i=0;i!=sol.leverOrder(root)[ix].size();++i)
           cout<<sol.leverOrder(root)[ix][i]<<" ";
          cout<<endl;}
    delete root->right->right;
     delete root->right->left;
     delete root->right;
     delete root->left;
     delete root;

     return 0;
    }
  • 相关阅读:
    99年人民币冠号大全
    9910的5种水印冠号发行量分布图
    儿童、青少年长身高的注意事项
    钱币评级流程与方法
    99版人民币收藏价值分析
    四、五版币冠字号发行量统计排行
    如何收藏第四套人民币大全套
    第四套荧光钞大全介绍
    小程序加载中提示实现
    微信小程序navigateBack如何带参数
  • 原文地址:https://www.cnblogs.com/Xylophone/p/3454610.html
Copyright © 2020-2023  润新知