LeetCode---Breadth-first traversal related to binary tree

Breadth first traversal

To be blunt, breadth-first traversal refers to the traversal from left to right layer by layer according to the idea of ​​binary tree hierarchy;
first, to complete this traversal idea, an auxiliary data structure queue is needed to complete; the
queue is first in, first out, It conforms to the logic of layer-by-layer traversal, but uses stack first-in-last-out which is suitable for simulating depth-first traversal, that is, recursive logic.
Not much nonsense, the example question above:

LeetCode102

Title description:
Give you a binary tree, please return the node value obtained by traversing it in a hierarchical order. (That is, visit all nodes layer by layer, from left to right).
Example:
Binary tree: [3,9,20,null,null,15,7],

Return the result of its level traversal:
[[3],[9,20], [15,7]].

Code solution:

class Solution {
    
    
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
    
    
        vector<vector<int>> result;
        queue<TreeNode*> que;
        if(root!=NULL)
            que.push(root);
        while(!que.empty())
        {
    
    
            vector<int> vec;   //用来存放节点的数值;
            int size=que.size();
            for(int i=0;i<size;i++)
            {
    
    
                TreeNode* node=que.front();    //保存que的头结点
                que.pop();                     
                vec.push_back(node->val);
                if(node->left)
                    que.push(node->left);
                if(node->right)
                    que.push(node->right);          
            }
            result.push_back(vec);
        }
        return result;
    }
};

For this code, if you understand it thoroughly, it can become a template code that solves breadth-first traversal, which is very easy to use;

LeetCode107 Binary Tree Level Traversal II

Given a binary tree, return its node value to traverse from the bottom to the top. (That is, from the layer where the leaf node is located to the layer where the root node is located, traverse from left to right layer by layer)

For example:
Given a binary tree [3,9,20,null,null,15,7],

Return its bottom-up level traversal as:
[[15,7], [9,20], [3]]

Thinking analysis: It's
just a small change of the above code;
code:

class Solution {
    
    
public:
        vector<vector<int>> levelOrderBottom(TreeNode* root) {
    
    
        vector<vector<int>> result;
        queue<TreeNode*> que;
        if(root!=NULL) que.push(root);
        while(!que.empty())
        {
    
    
            vector<int> vec;
            int size=que.size();
            for(int i=0;i<size;i++)
            {
    
    
                TreeNode* node=que.front();   //找到队列的头结点
                que.pop();                    //弹出头结点
                vec.push_back(node->val);
                if(node->left) que.push(node->left);
                if(node->right) que.push(node->right);
            }
            result.push_back(vec);
        }
        reverse(result.begin(),result.end());     //利用库函数逆置二维数组;
        return result;
    }
};

Right view of LeetCode199 binary tree

Title description:
Given a binary tree, imagine yourself standing on the right side of it, and return the node values ​​that can be seen from the right side in order from top to bottom.

Example:
Input: [1,2,3,null,5,null,4]
Output: [1, 3, 4]
Explanation:

1 <—
/
2 3 <—
\
5 4 <—
Thinking analysis: I
really want to. As long as the value of the rightmost node, it is only necessary to judge whether this node is the rightmost node when the layer sequence is traversed, and if it is, record this node.
Code:

class Solution {
    
    
public:
    vector<int> rightSideView(TreeNode* root) {
    
    
        //思路:在层序遍历的时候,找到最后一个数字,添加到vec中,最终返回vec;    此处的方法是广度优先遍历
        vector<int> result;
        queue<TreeNode*> que;
        if(root!=NULL) 
        {
    
    
            que.push(root);
            //result.push_back(root->val);
        }
        while(!que.empty())
        {
    
    
            int size=que.size();
            for(int i=0;i<size;i++)
            {
    
    
                TreeNode* node=que.front();
                que.pop();
                if(i==(size-1))
                {
    
    
                   result.push_back(node->val); 
                }
                if(node->left)   que.push(node->left);
                if(node->right)  que.push(node->right);
            }
        }
        return result;
    }
};

Leetcode637 Binary tree layer average

Title description:
Given a non-empty binary tree, return an array consisting of the average value of each level of nodes.
Example 1:

Input:
3
9 20
15 7
Output: [3, 14.5, 11]

Analysis of the train of thought: It is
still just a small change of the above code: one more record the data and sum of each layer, and then output the average value of each layer;
code:

class Solution {
    
    
public:
    vector<double> averageOfLevels(TreeNode* root) {
    
    
        vector<double> result;
        queue<TreeNode*> que;
        if(root!=NULL)  que.push(root);

        while(!que.empty())
        {
    
    
            int size=que.size();
            double sum=0;        //注意最后的平均值可能是double类型的,这里不能把sum定义成int
            for(int i=0;i<size;i++)
            {
    
    
                TreeNode* node=que.front();
                que.pop();
                sum=sum+node->val;
                if(node->left) que.push(node->left);
                if(node->right) que.push(node->right);
            }
            result.push_back((sum/size));
        }
        return result;
    }
};

LeetCode429 N-ary tree traversal

Note that the node definition of this question is different from before:
node definition:

class Node {
    
    
public:
    int val;
    vector<Node*> children;
    Node() {
    
    }
    Node(int _val) {
    
    
        val = _val;
    }
    Node(int _val, vector<Node*> _children) {
    
    
        val = _val;
        children = _children;
    }
};

Problem-solving idea:
the same as the above routine, except that when adding to the queue, add N children into the queue instead of the left and right children of the binary tree.
Code:

class Solution {
    
    
public:
    vector<vector<int>> levelOrder(Node* root) {
    
    
        vector<vector<int>> result;
        queue<Node*> que;
        if(root!=NULL) que.push(root);
        while(!que.empty())
        {
    
    
            int size=que.size();
            vector<int> vec;        //储存val
            for(int i=0;i<size;i++)
            {
    
    
                 Node* node=que.front();
                 que.pop();
                 vec.push_back(node->val);
                 for(int i=0;i<node->children.size();i++)
                 {
    
    
                     if(node->children[i]!=NULL)
                     {
    
    
                         que.push(node->children[i]);
                     }
                 }

            }
            result.push_back(vec);
       }
       return result;
    }
};

LeetCode 226 Flip Binary Tree

Note that here you can use the non-recursive traversal of layer sequence to flip a binary tree;
analysis of thinking:
flip a binary tree, only need to traverse each node, exchange the left and right child nodes of each node, you can achieve the whole tree The inversion of the tree.
Code:

        TreeNode* invertTree(TreeNode* root) {
    
    
            queue<TreeNode*> que;              //层序遍历需要借助队列
            if(root!=NULL)  que.push(root);
            while(!que.empty())
            {
    
    
                int size=que.size();
                for(int i=0;i<size;i++)
                {
    
    
                    TreeNode* node=que.front();
                    que.pop();
                    //只要在遍历每个节点的时候,交换子节点的左右位置即可;
                    swap(node->left,node->right);
                    if(node->left) que.push(node->left);                //因为是队列,所以先左再右
                    if(node->right) que.push(node->right);
                }
            }
            return root;
        }

to sum up

See through one question, and be able to solve six questions!

Guess you like

Origin blog.csdn.net/ALITAAAA/article/details/109356538