• Binary Tree Level Order Traversal II


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

    题意:给一棵二叉树,返回层次遍历后,从叶节点到根回溯的结果。

    解题思路:对二叉树进行层次遍历,用count来记录每层的结点数,用队列que实现,最后将层次遍历的结果反序则可。代码应该不难看懂。

    /**
     * Definition for binary tree
     * 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) {
            vector<vector<int> > ans;
            vector<vector<int> > result;
    TreeNode* cur;
    int count = 0; queue<TreeNode*> que; if(root != NULL) {
    //先处理根结点 vector
    <int> tmp; tmp.push_back(root->val); ans.push_back(tmp); if(root->left != NULL) { count++; que.push(root->left); } if(root->right != NULL){ count++; que.push(root->right); } while(!que.empty()) { int k = count; vector<int> tt; count = 0; for(int i=0;i<k; i++) { cur = que.front(); que.pop(); tt.push_back(cur->val); if(cur->left != NULL) { count++; que.push(cur->left); } if(cur->right != NULL){ count++; que.push(cur->right); } } ans.push_back(tt); } } if(ans.size() > 0) { for(int j = ans.size()-1; j >= 0; j--) result.push_back(ans[j]); } return result; } };
  • 相关阅读:
    数据库的逻辑结构与物理结构
    HTTP笔记整理(1)
    当我看懂这张图的时候很痛苦~~~
    软件测试面试分享(转)
    达梦(DM)数据库Linux部署安装
    进阶的小小测试~软件测试不得不知的基础知识
    软件测试分类
    浅说软件需求分析
    浅说《测试用例》----给测试新手的
    软件测试人员两极分化
  • 原文地址:https://www.cnblogs.com/chenbjin/p/3719621.html
Copyright © 2020-2023  润新知