【LeetCode】199.Binary Tree Right Side View(Medium)解题报告
2018-03-17 19:51
405 查看
【LeetCode】199.Binary Tree Right Side View(Medium)解题报告
题目地址:https://leetcode.com/problems/binary-tree-right-side-view/description/
题目描述:
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.
Solution1:
Solution2:
Date:2018年3月17日
题目地址:https://leetcode.com/problems/binary-tree-right-side-view/description/
题目描述:
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].
Solution1:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } time : O(n) space : O(n) */ class Solution { public List<Integer> rightSideView(TreeNode root) { List<Integer> res = new ArrayList<>(); if(root == null) return res; helper(res , root , 0); return res; } public void helper(List<Integer> res,TreeNode root,int level){ if(root == null) return; if(res.size() == level){ res.add(root.val); } helper(res,root.right,level+1); helper(res,root.left,level+1); } }
Solution2:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } time : O(n) space : O(n) */ class Solution { public List<Integer> rightSideView(TreeNode root) { List<Integer> res = new ArrayList<>(); if(root == null) return res; Queue<TreeNode> queue = new LinkedList<>(); queue.offer(root); while(!queue.isEmpty()){ int size = queue.size(); for(int i=0 ; i<size ; i++){ TreeNode cur = queue.poll(); if(i == 0) res.add(cur.val); if(cur.right!=null) queue.offer(cur.right); if(cur.left!=null) queue.offer(cur.left); } } return res; } }
Date:2018年3月17日
相关文章推荐
- 【LeetCode】75.Sort Colors(Medium)解题报告
- 【LeetCode】351.Android Unlock Patterns(Medium)解题报告
- 【LeetCode】60.Permutation Sequence(medium)解题报告
- 【LeetCode】103. Binary Tree Zigzag Level Order Traversal(Medium)解题报告
- LeetCode解题报告 394. Decode String [medium]
- 【LeetCode】623.Add One Row to Tree(Medium)解题报告
- 【LeetCode】57.Insert Interval(Medium)解题报告
- 【LeetCode】275.H-Index II(Medium)解题报告
- 【LeetCode】280.Wiggle Sort (Medium)(带锁题)解题报告
- 【LeetCode】94.Binary Tree Inorder Traversal(Medium)解题报告
- LeetCode解题报告 445. Add Two Numbers II [medium]
- 【LeetCode】152.Maximum Product Subarray(Medium)解题报告
- LeetCode解题报告 55. Jump Game [medium]
- 【LeetCode】334.Increasing Triplet Subsequence(Medium)解题报告
- 【LeetCode】406.Queue Reconstruction by Height(Medium)解题报告
- LeetCode解题报告 279. Perfect Squares [medium]
- LeetCode解题报告 357. Count Numbers with Unique Digits [medium]
- 【LeetCode】117.Populating Next Right Pointers in Each Node II(Medium)解题报告
- 【LeetCode】244.Shortest Word Distance II(Medium)解题报告
- 【LeetCode】648.Replace Words(Medium)解题报告