Leetcode-199. Binary Tree Right Side View

来源:互联网 发布:华为软件工程师 知乎 编辑:程序博客网 时间:2024/06/08 03:07

前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发CSDN,mcf171专栏。

博客链接:mcf171的博客

——————————————————————————————

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

这个题目没啥好说的,先遍历根节点,再遍历右节点,再遍历做节点。时间复杂度O(n)Your runtime beats 79.24% of java submissions.

public class Solution {    private int see_high = 0;    public List<Integer> rightSideView(TreeNode root) {        List<Integer> results = new ArrayList<Integer>();search(root,results,0);return results;    }    public void search(TreeNode root,List<Integer> results, int depth){if(root == null) return;if(depth >= see_high){    results.add(root.val);    see_high++;    }search(root.right,results,depth+1);search(root.left,results,depth +1);    }}





0 0
原创粉丝点击