1. 程式人生 > >代碼題(7)— 二叉樹的層次遍歷

代碼題(7)— 二叉樹的層次遍歷

通過 push_back gin 節點 null node desc 二叉 for

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.insert(res.begin(), temp); 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;
    }
};

代碼題(7)— 二叉樹的層次遍歷