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


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


  • 相关阅读:
    VUE集成keycloak和Layui集成keycloak
    iscsi基本命令
    Linux网卡bond模式
    Unmount and run xfs_repair
    Centos7 升级过内核 boot分区无法挂载修
    Centos7 误删除bin/sbin之类的恢复
    QSS 记录
    #pragma 小节
    解决Github打不开问题
    判断数据是否在指定区间内
  • 原文地址:https://www.cnblogs.com/zclzqbx/p/4687093.html
Copyright © 2011-2022 走看看