zoukankan      html  css  js  c++  java
  • [LeetCode] Binary Tree Level Order Traversal

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

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

        3
       / 
      9  20
        /  
       15   7
    

    return its level order traversal as:

    [
      [3],
      [9,20],
      [15,7]
    ]
    
    /**
     * 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> > levelOrder(TreeNode *root) {
            // IMPORTANT: Please reset any member data you declared, as
            // the same Solution instance will be reused for each test case.
            vector<vector<int>> ans;
            if(root == NULL) return ans;
            vector<TreeNode*> cur;
            vector<int> curVal;
            cur.push_back(root);
            curVal.push_back(root -> val);
            while(!cur.empty())
            {
                ans.push_back(curVal);
                vector<TreeNode*> tmp;
                vector<int> tmpVal;
                for(int i = 0;i < cur.size();i++)
                {
                    if(cur[i] -> left != NULL) 
                    {
                        tmp.push_back(cur[i] -> left);
                        tmpVal.push_back(cur[i] -> left -> val);
                    }
                    if(cur[i] -> right != NULL) 
                    {
                        tmp.push_back(cur[i] -> right);
                        tmpVal.push_back(cur[i] -> right -> val);
                    }
                }
                cur = tmp;
                curVal = tmpVal;
            }
            return ans;
        }
    };
  • 相关阅读:
    如何在vue项目中使用md5加密
    对象的预定义属性及方法
    setInterval()调用其他函数时候报错
    Why Lua?
    Docker入门
    HashTable源码简单介绍
    VM12中CentOS7以NAT方式连接网络的方法
    Java垃圾回收(整理)
    Java进程&线程(整理)
    java集合树状结构及源码
  • 原文地址:https://www.cnblogs.com/changchengxiao/p/3417530.html
Copyright © 2011-2022 走看看