码迷,mamicode.com
首页 > 其他好文 > 详细

【leetcode】Binary Tree Level Order Traversal I & II

时间:2015-07-07 16:30:04      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:

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

分层遍历二叉树,用BFS即可

class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
        queue<TreeNode*> Q;
        vector<vector<int>> ans;
        Q.push(root);
        while(!Q.empty())
        {
            int e = Q.size(); //当前层的结束位置
            vector<int> partans;
            for(int i = 0; i < e; i++)
            {
                TreeNode * p = Q.front();
                Q.pop();
                if(NULL != p)
                {
                    partans.push_back(p->val);
                    Q.push(p->left);
                    Q.push(p->right);
                }
            }
            if(!partans.empty())
                ans.push_back(partans);
        }
        return ans;
    }
};

网上DFS的代码:

class Solution {
protected:
    vector<vector<int>> ans;
    void dfs(TreeNode *root, int height){
        if (root == NULL) 
            return;
        while (ans.size() <= height)
            ans.push_back(vector<int>());
        ans[height].push_back(root->val);
        dfs(root->left, height + 1);
        dfs(root->right, height + 1);
    }

public:
    vector<vector<int>> levelOrder(TreeNode* root) {
       dfs(root, 0);
        return ans;    
    }
};

 

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

 

跟上面只是顺序变了,加个reverse就行了。

 

【leetcode】Binary Tree Level Order Traversal I & II

标签:

原文地址:http://www.cnblogs.com/dplearning/p/4627247.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!