代码题(7)— 二叉树的层次遍历

1、102. 二叉树的层次遍历

给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。

例如:
给定二叉树: [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

返回其层次遍历结果:

[
  [3],
  [9,20],
  [15,7]
]
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
        vector<vector<int>> res;
        if(root == nullptr)
            return res;
        queue<TreeNode*> qNode;
        qNode.push(root);
        TreeNode* cur = nullptr;
        while(!qNode.empty())
        {
            vector<int> temp;
            int num = qNode.size();
            for(int i=0;i<num;++i)
            {
                cur = qNode.front();
                temp.push_back(cur->val);
                qNode.pop();
                if(cur->left != nullptr)
                    qNode.push(cur->left);
                if(cur->right != nullptr)
                    qNode.push(cur->right);
            }
            res.push_back(temp);
        }
        return res;
    }
};
2、103. 二叉树的锯齿形层次遍历

给定一个二叉树,返回其节点值的锯齿形层次遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。

例如:
给定二叉树 [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

返回锯齿形层次遍历如下:

[
  [3],
  [20,9],
  [15,7]
]
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
        vector<vector<int>> res;
        if(root == nullptr)
            return res;
        stack<TreeNode*> st1, st2;
        st1.push(root);
        while(!st1.empty() || !st2.empty())
        {
            if(!st1.empty())
            {
                vector<int> temp;
                while(!st1.empty())
                {
                    TreeNode* cur = st1.top();
                    temp.push_back(cur->val);
                    st1.pop();
                    if(cur->left)
                        st2.push(cur->left);
                    if(cur->right)
                        st2.push(cur->right);
                }
                res.push_back(temp);
            }
            
            if(!st2.empty())
            {
                vector<int> temp;
                while(!st2.empty())
                {
                    TreeNode* cur = st2.top();
                    temp.push_back(cur->val);
                    st2.pop();
                    if(cur->right)
                        st1.push(cur->right);
                    if(cur->left)
                        st1.push(cur->left);
                }
                res.push_back(temp);
            }
            
        }
        return res;
    }
};



猜你喜欢

转载自www.cnblogs.com/eilearn/p/9217615.html