首页 > 代码库 > Binary Tree Level Order Traversal

Binary Tree Level Order Traversal

问题:从上到下打印二叉树的每一行
分析:先搜出二叉树的高度,然后遍历高度,每次搜索一个高度

class Solution {public:    int dfs(TreeNode *root)    {        if(root==NULL) return 0;        if(root->left==NULL && root->right==NULL) return 1;        return max(dfs(root->left),dfs(root->right))+1;    }    void Ddfs(TreeNode *root,int t,vector<int> &vec,int step)    {        if(step==t) vec.push_back(root->val);        if(root->left)  Ddfs(root->left,t,vec,step+1);        if(root->right) Ddfs(root->right,t,vec,step+1);    }    vector<vector<int> > levelOrder(TreeNode *root) {        int height=dfs(root);        vector<vector<int> > vec1;        for(int i=1;i<=height;i++)        {            vector<int> vec2;            Ddfs(root,i,vec2,1);            vec1.push_back(vec2);        }        return vec1;    }};