Monday, April 28, 2014

[LeetCode] Binary Tree Level Order Traversal I & II

Binary Tree Level Order Traversal I
Problem statement (link):
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]
]
Analysis:
Just add a level variable to indicate whether we are at a new level and increase the size of output vector<vector<int>>.

Code:
/**
 * 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) {
        vector<vector<int> > nodeV;
        if (root==NULL) return nodeV;

        int level = 0;
        helper(nodeV, root, level);

        return nodeV;
    }
  
    void helper(vector<vector<int> > &nodeV, TreeNode *node, int level) {
        if (node==NULL) return;

        if (level >= nodeV.size())
            nodeV.push_back(vector<int> ());
        nodeV[level].push_back(node->val);

        if (node->left != NULL) helper(nodeV, node->left, level+1);
        if (node->right !=NULL) helper(nodeV, node->right, level+1);
    }
};

Binary Tree Level Order Traversal II
Problem Statement (link):
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],
]
Analysis:
Same as the previous problem, we just need to reverse the output vector order.

Code:
class Solution {
public:
    vector<vector<int> > levelOrderBottom(TreeNode *root) {
        vector<vector<int>> out;
        if (root==NULL) return out;

        int level=0;
        recur(out, root, level);

        // reverse order
        for (int i=0; i<out.size()/2; i++) {
            vector<int> tmp=out[i];
            out[i]=out[out.size()-i-1];
            out[out.size()-i-1]=tmp;
        }
        return out;
    }

    void recur(vector<vector<int>>& out, TreeNode* node, int level) {
        if (node==NULL) return;
        if (out.size()<=level)
            out.push_back(vector<int> ());

        out[level].push_back(node->val);
        recur(out, node->left, level+1);
        recur(out, node->right, level+1);
    }
};

No comments:

Post a Comment