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

Binary Tree Right Side View 二叉树层序遍历变形

时间:2015-04-11 17:52:51      阅读:109      评论:0      收藏:0      [点我收藏+]

标签:leetcoode   binary tree right si   层序遍历   

Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.

For example:
Given the following binary tree,

   1            <---
 /   2     3         <---
 \       5     4       <---

You should return [1, 3, 4].

https://leetcode.com/problems/binary-tree-right-side-view/ 题目位置

其实就是层序遍历,然后记录每一层中节点,最后一个的值

经常做到和层序相关的题目,之前是一个二叉树的Z扫描的问题,和这里基本上才用了一样的数据结构,所以很熟悉,写完就AC。

利用了一个vector存储每一层的元素,然后进行一个简单的递归 

如果二叉树中没有对每一行有特别需要的要求,那么就是可以直接利用 队列,如果有要求,也可以在队列中加入一个类似NULL节点表示结束

http://blog.csdn.net/xietingcandice/article/details/44939919 


/**
 * 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<int> res;
    vector<int> rightSideView(TreeNode *root) { //其实就是每一行的最后一个节点
        res.clear();
        if(root == NULL)
        {
            return res;
        }
        vector<TreeNode*> node;
        node.push_back(root);
        GetNum(node);
        return res;
    }
    void GetNum(vector<TreeNode*> &node)
    {
        if(node.empty())
        {
            return;
        }
        vector<TreeNode*>pNode;
        //<获取当前层最右边节点的值
        res.push_back(node[node.size()-1]->val);
        //<按顺序获取他的子节点
        for(int i = 0; i < node.size();i++)
        {
            TreeNode * root = node[i];
            if(root->left)
            {
                pNode.push_back(root->left);
            }
            if(root->right)
            {
                pNode.push_back(root->right);
            }
        }
        GetNum(pNode);
    }
};


Binary Tree Right Side View 二叉树层序遍历变形

标签:leetcoode   binary tree right si   层序遍历   

原文地址:http://blog.csdn.net/xietingcandice/article/details/44997293

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