• 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; } };
  • 相关阅读:
    函数练习之计算机
    函数练习小程序
    Java—Day5课堂练习
    mysql-用户权限管理
    liunx-tail 实时显示文件内容
    Linux-diff --比较两个文件并输出不同之处
    linux-查找某目录下包含关键字内容的文件
    mysql-允许远程连接
    mysql-基本操作
    liunx-指令
  • 原文地址:https://www.cnblogs.com/chenbjin/p/3719621.html
Copyright © 2020-2023  润新知