2

二叉树之
字形级别顺序遍历给定一棵二叉树,返回其节点值的之字形级别顺序遍历。(即从左到右,然后从右到左为下一级和交替)。

例如:给定二叉树 {3,9,20,#,#,15,7},

        3 
       / \ 
      9   20 
     / \ 
   15   7 

其之字形水平顺序遍历返回为:

[   
    [3],
    [20,9],
    [15,7]
]


个人认为
时间复杂度= O(n * height),n是节点数,height是给定二叉树的高度。

   getHeight()             => O(n) 
   traverseSpecificLevel() => O(n)
   reverseVector()         => O(n)
   swap()                  => O(1)


C++

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
#include <vector>
using namespace std;

class Solution {
public:
    vector<vector<int> > zigzagLevelOrder(TreeNode *root) {
        vector<vector<int>> list;

        // Input validation.
        if (root == NULL) return list;

        // Get the height of the binary tree.
        int height = getHeight(root);

        bool left_to_right = true;
        for (int level = 0; level <= height; level ++) {
            vector<int> subList;
            traverseSpecificLevel(root, level, subList);

            if (left_to_right == true) {
                // Add subList into list.
                list.push_back(subList);
                // Update left_to_right flag.
                left_to_right = false;

            } else {
                // Reverse subList.
                reverseVector(subList);
                // Add reversed subList into list.
                list.push_back(subList);
                // Update left_to_right flag.
                left_to_right = true;
            }
        }
        return list;
    }

    int getHeight(TreeNode *root) {
        // Base case.
        if (root == NULL || (root->left == NULL && root->right == NULL)) return 0;
        else return 1 + max(getHeight(root->left), getHeight(root->right));
    }

    void traverseSpecificLevel(TreeNode *root, int level, vector<int> &subList) {
        // Base case.
        if (root == NULL) return;
        if (level == 0) {
            subList.push_back(root->val);
            return;
        }

        // Do recursion.
        traverseSpecificLevel(root->left, level - 1, subList);
        traverseSpecificLevel(root->right, level - 1, subList);
    }

    void reverseVector(vector<int> &list) {
        // Input validation.
        if (list.size() <= 1) return;

        int start = 0;
        int end = list.size() - 1;
        while (start < end) {
            swap(list, start, end);

            start ++;
            end --;
        }
    }

    void swap(vector<int> &list, int first, int second) {
        int tmp = list[first];
        list[first] = list[second];
        list[second] = tmp;
    }
};
4

1 回答 1

1

您可以在线性时间内完成。创建一个大小为 max_height 的向量 > 结果。递归遍历树,维护节点的级别。对于每个节点,将其值推回结果[级别]。不仅仅是反转结果[1],结果[3],...。

顺便说一句,有一个swap(x,y)函数和reverse(a.begin(), a.end())函数(其中a是一个向量),您可以使用它们而不是自己实现它们。包括algorithm它。

于 2014-07-07T15:11:19.780 回答