[Locked] Binary Tree Vertical Order Traversal

Binary Tree Vertical Order Traversal

Given a binary tree, return the vertical order traversal of its nodes' values. (ie, from top to bottom, column by column).

If two nodes are in the same row and column, the order should be from left to right.

Examples:
Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its vertical order traversal as:

[
  [9],
  [3,15],
  [20],
  [7]
]

Given binary tree [3,9,20,4,5,2,7],

    _3_
   /   \
  9    20
 / \   / \
4   5 2   7

return its vertical order traversal as:

[
  [4],
  [9],
  [3,5,2],
  [20],
  [7]
]

分析:

  从根节点出发走的是一左一右或者一右一左的路径到达某节点,那么这个节点的列数可看做0;如果是两左,则为-2;为两右为2。

代码:

void dfs(TreeNode *node, int col, vector<vector<int> > &vleft, vector<vector<int> > &vright) {
    if(!node)
        return;
    //在根节点右边
    if(col > 0) {
        //列编号超出了vright边界,则扩展边界
        while(col >= vright.size())
            vright.push_back(vector<int> ());
        vright[col].push_back(node->val);
    }
    //在根节点列左边或者中间
    else {
        //列编号超出了vleft边界,则扩展边界
        while(-col >= vleft.size())
            vleft.push_back(vector<int> ());
        vleft[-col].push_back(node->val);
    }
    dfs(node->left, col - 1, vleft, vright);
    dfs(node->right, col + 1, vleft, vright);
    return;
}
vector<vector<int> > verticalorder(TreeNode *root) {
    vector<vector<int> > vleft, vright;
    dfs(root, 0, vleft, vright);
    //翻转vleft,然后与vright拼接
    reverse(vleft.begin(), vleft.end());
    vleft.insert(vleft.end(), vright.begin() + 1, vright.end());
    return vleft;
}

 

posted @ 2016-02-27 10:24  CarlGoodman  阅读(175)  评论(0编辑  收藏  举报