题目描述:
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].
思路:
BFS,存最右边的节点,
LeetCode Binary Tree Right Side View
。实现代码:
/** * Definition for a binary tree node. * public class TreeNode { * public int val; * public TreeNode left; * public TreeNode right; * public TreeNode(int x) { val = x; } * } */public class Solution { public IList<int>RightSideView(TreeNode root) { if(root == null){ return new List<int>(); } var result = new List<int>(); RightView(new List<treenode>(){root}, result); return result; } public void RightView(IList<treenode>nodes, IList<int>result) { if(!nodes.Any()){ return; } // add last node which is on the most right position result.Add(nodes.Last().val); // BFS var children = new List<treenode>(); foreach(var n in nodes){ var nl = Children(n); if(nl.Any()){ children.AddRange(nl); } } RightView(children, result); }private IList<treenode>Children(TreeNode node){ if(node == null){ return new List<treenode>(); } var list = new List<treenode>(); if(node.left != null){ list.Add(node.left); } if(node.right != null){ list.Add(node.right); } return list;}}</treenode></treenode></treenode></treenode></int></treenode></treenode></int></int></int>