加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

[LeetCode] Binary Tree Right Side View

发布时间:2020-12-13 20:42:34 所属栏目:PHP教程 来源:网络整理
导读: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]

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

解题思路

层次遍历法,找出每层最右真个结点。

实现代码1

/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x),left(NULL),right(NULL) {} * }; */ // Runtime:7ms class Solution { public: vector<int> rightSideView(TreeNode *root) { vector<int> nums; queue<TreeNode*> nodes; if (root != NULL) { nodes.push(root); } TreeNode *cur; while (!nodes.empty()) { int size = nodes.size(); for (int i = 0; i < size; i++) { cur = nodes.front(); nodes.pop(); if (cur->left != NULL) { nodes.push(cur->left); } if (cur->right != NULL) { nodes.push(cur->right); } } nums.push_back(cur->val); } return nums; } };

实现代码2

# Definition for a binary tree node # class TreeNode: # def __init__(self,x): # self.val = x # self.left = None # self.right = None # Runtime:74ms class Solution: # @param root,a tree node # @return a list of integers def rightSideView(self,root): nums = [] if root == None: return nums nodes = [root] while nodes: size = len(nodes) for i in range(size): cur = nodes.pop(0) if cur.left != None: nodes.append(cur.left) if cur.right != None: nodes.append(cur.right) nums.append(cur.val) return nums;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读