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

相关文章:

  • 2021-04-24
  • 2021-04-09
  • 2021-11-15
  • 2022-01-20
  • 2022-02-17
  • 2022-02-24
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-04-01
  • 2021-04-13
  • 2021-11-07
  • 2021-05-27
  • 2021-09-03
  • 2021-10-08
  • 2021-09-20
相关资源
相似解决方案