【Lintcode】760. Binary Tree Right Side View

题目地址:

https://www.lintcode.com/problem/binary-tree-right-side-view/description

给定一棵二叉树,返回其从右向左看时看到的所有节点。

法1:BFS。分层遍历即可,每次都将最右边的值加入最终结果。代码如下:

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class Solution {
    /**
     * @param root: the root of the given tree
     * @return: the values of the nodes you can see ordered from top to bottom
     */
    public List<Integer> rightSideView(TreeNode root) {
        // write your code here
        List<Integer> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
        	// 分层遍历需要记录一下队列的size
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode x = queue.poll();
                if (i == 0) {
                    res.add(x.val);
                }
                // 先加右儿子再加左儿子,这样每层第一个节点就可以直接加入res
                if (x.right != null) {
                    queue.offer(x.right);
                }
                if (x.left != null) {
                    queue.offer(x.left);
                }
            }
        }
        
        return res;
    }
}

class TreeNode
    int val;
    TreeNode left, right;
    TreeNode(int x) {
        val = x;
    }
}

时空复杂度 O ( n ) O(n) O(n)

法2:DFS。可以将当前节点深度作为参数在递归时传递下去,并且按照先序遍历的顺序做DFS。如果是第一次遍历到某一深度,则将节点的值直接加入res,否则覆盖res在当前深度的值。代码如下:

import java.util.ArrayList;
import java.util.List;

public class Solution {
    /**
     * @param root: the root of the given tree
     * @return: the values of the nodes you can see ordered from top to bottom
     */
    public List<Integer> rightSideView(TreeNode root) {
        // write your code here
        List<Integer> res = new ArrayList<>();
        dfs(root, 0, res);
        return res;
    }
    
    private void dfs(TreeNode root, int depth, List<Integer> res) {
        if (root == null) {
            return;
        }
        // 如果是第一次遍历到depth这个深度,则直接将值加入res;
        // 否则直接覆盖res中当前深度的值
        if (depth == res.size()) {
            res.add(root.val);
        } else {
            res.set(depth, root.val);
        }
        // 先遍历左子树,
        dfs(root.left, depth + 1, res);
        dfs(root.right, depth + 1, res);
    }
}

时间复杂度 O ( n ) O(n) O(n),空间 O ( h ) O(h) O(h)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值