leetcode 199 二叉树的右视图

简介

常规方法, BFS

code

这里使用了隔板法, 其实有概率出错的.

class Solution {
public:
    vector<int> rightSideView(TreeNode* root) {
        // bfs
        queue<TreeNode*> q;
        vector<int> rlt;
        if(root == nullptr){
            return rlt;
        }
        q.push(root);
        TreeNode * p = new TreeNode(1e9);
        q.push(p);
        
        while(!q.empty()){
            TreeNode* t = q.front();
            q.pop();

            if(t->left){
                q.push(t->left);
            }
            if(t->right){
                q.push(t->right);
            }
            if(q.front()->val == 1e9){
                rlt.push_back(t->val);
                q.pop();
                if(q.empty()){
                    break;
                }
                q.push(p);
            }
        }
        return rlt;
    }
};
class Solution {
    List<Integer> res = new ArrayList<>();

    public List<Integer> rightSideView(TreeNode root){
        dfs(root, 0);
        return res;
    }
    private void dfs(TreeNode root, int depth) {
        if(root == null) {
            return;
        }
        // 先访问当前节点, 再递归地访问右子树和左子树
        if(depth == res.size()) {
            res.add(root.val);
        }
        depth++;
        dfs(root.right, depth);
        dfs(root.left, depth);
    }
}

java 的思路很巧妙, dfs, 时间和效率都较快.
if(depth == res.size()) {
res.add(root.val);
}
这一部分很巧妙, 每一层的最先被遍历到的节点放入了dfs中. 其他的被排除了, 根右左的遍历方式.

Hope is a good thing,maybe the best of things,and no good thing ever dies.----------- Andy Dufresne
原文地址:https://www.cnblogs.com/eat-too-much/p/14774796.html