• leetcode 199. Binary Tree Right Side View 、leetcode 116. Populating Next Right Pointers in Each Node 、117. Populating Next Right Pointers in Each Node II


    leetcode 199. Binary Tree Right Side View

    这个题实际上就是把每一行最右侧的树打印出来,所以实际上还是一个层次遍历。

    依旧利用之前层次遍历的代码,每次大的循环存储的是一行的节点,最后一个节点就是想要的那个节点

    class Solution {
    public:
        vector<int> rightSideView(TreeNode* root) {
            vector<int> result;
            if(root == NULL)
                return result;
            queue<TreeNode*> q;
            q.push(root);
            while(!q.empty()){
                result.push_back(q.back()->val);
                for(int i = q.size();i > 0;i--){
                    TreeNode* node = q.front();
                    if(node->left)
                        q.push(node->left);
                    if(node->right)
                        q.push(node->right);
                    q.pop();
                }          
            }
            return result;
        }
    };

    leetcode 116. Populating Next Right Pointers in Each Node

    这个题和199题类似,也是层序遍历,且最后一个的node的next为NULL;

    class Solution {
    public:
        Node* connect(Node* root) {
            if(root == NULL)
                return NULL;
            queue<Node*> q;
            q.push(root);
            while(!q.empty()){    
                for(int i = q.size();i > 0;i--){
                    Node* node = q.front();
                    q.pop();
                    if(i != 1)
                        node->next = q.front();
                    if(node->left)
                        q.push(node->left);
                    if(node->right)
                        q.push(node->right);
                }         
            }
            return root;
        }
    };

    117. Populating Next Right Pointers in Each Node II

    这个题与116不同在于,树不再是完全二叉树。对于递归的方法不同,对于非递归,同一个代码完全可以解决这两个问题

  • 相关阅读:
    mysql 约束条件介绍
    mysql 约束条件目录
    mysql 日期类型
    mysql float 浮点型
    mysql int 整数类型 解释显示宽度 和 存储宽度
    mysql 整数类型 数值类型 tinyint
    【洛谷P4096】Eden 的博弈树
    【GMOJ6824】英雄联盟
    【GMOJ6826】隔膜
    【POJ 2420】A Star not a Tree?
  • 原文地址:https://www.cnblogs.com/ymjyqsx/p/10676750.html
Copyright © 2020-2023  润新知