• LeetCode 199. Binary Tree Right Side View


    题目

    题意:假如你在一棵二叉树的右边,往左看,能看到哪些元素。

    题解:广搜,每一层的最右边元素即可。

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    struct Node
    {
        TreeNode* node;
        int num;
        Node(){}
        Node(TreeNode* node,int num)
        {
            this->node = node;
            this->num = num;
        }
    };
    class Solution {
    public:
        vector<int> ans;
        vector<int> rightSideView(TreeNode* root) {
            
            if(root==NULL)
                return ans;
            queue<Node> q;
            q.push(Node(root,0));
            
            int num = 0;
            while(!q.empty())
            {
                Node term = q.front();
                q.pop();
                
                if(q.empty()||q.front().num != term.num)
                {
                    ans.push_back(term.node->val);
                }
                
                if(term.node->left!=NULL)
                    q.push(Node(term.node->left,term.num+1));
                if(term.node->right!=NULL)
                    q.push(Node(term.node->right,term.num+1));
            }
            
            return ans;
            
            
        }
        
    };
    
  • 相关阅读:
    OpenCV 简介
    无缝滚动
    Date 与 switch的运用
    js object(对象)
    arr.sort()排序方法
    删除
    评分
    延时提示框
    数字相加求和
    自定义右键菜单
  • 原文地址:https://www.cnblogs.com/dacc123/p/12302316.html
Copyright © 2020-2023  润新知