zoukankan      html  css  js  c++  java
  • leetCode(22):Binary Tree Level Order Traversal II 分类: leetCode 2015-06-22 09:09 145人阅读 评论(0) 收藏

    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]
    ]

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        vector<vector<int>> levelOrderBottom(TreeNode* root) {
            queue<TreeNode*> nodes;
        	vector< vector<int> > result;
        	vector<int> tmp;
        	if(NULL==root)
        		return result;
        	nodes.push(root);
        	while(!nodes.empty())
        	{
        		int length=nodes.size();
        		int i=0;
        		while(i<length)
        		{//弹出本层所有结点后,跳出循环,length的值在循环时是不会改变的
        			TreeNode* tmpNode=nodes.front();
        			tmp.push_back(tmpNode->val);
        			if(tmpNode->left)
        				nodes.push(tmpNode->left);
        			if(tmpNode->right)
        				nodes.push(tmpNode->right);
        			nodes.pop();
        			i++;
        		}
        		result.push_back(tmp);
        		tmp.clear();
        	}
        	reverse(result.begin(),result.end());
        	return result;
        }
    };


    又是层序遍历的方式,层序遍历反复出现过多次:求二叉树的最小深度、右侧能看到的结点、统计特殊形式的二叉树结点个数...


  • 相关阅读:
    RocketMQ Message hasn't been sent. Caused by No route info of this topic, test-topic
    Barrier
    WPF之资源
    WPF之命令
    WPF之事件
    WPF之属性
    多路Binding
    Binding的数据转换
    Binding的数据校验
    为Binding指定源的方法
  • 原文地址:https://www.cnblogs.com/zclzqbx/p/4687093.html
Copyright © 2011-2022 走看看