zoukankan      html  css  js  c++  java
  • 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不同在于,树不再是完全二叉树。对于递归的方法不同,对于非递归,同一个代码完全可以解决这两个问题

  • 相关阅读:
    链表中环的入口节点
    链表中倒数第k个节点
    调整数组顺序使奇数位于偶数前面
    53. Maximum Subarray
    42. Trapping Rain Water
    48. Rotate Image
    css技巧一
    html语义
    label标签表单响应
    CSS清除浮动
  • 原文地址:https://www.cnblogs.com/ymjyqsx/p/10676750.html
Copyright © 2011-2022 走看看