leetcode 114. Flatten Binary Tree to Linked List

Given a binary tree, flatten it to a linked list in-place.

For example,
Given

         1
        / \
       2   5
      / \   \
     3   4   6

The flattened tree should look like:
   1
    \
     2
      \
       3
        \
         4
          \
           5
            \
             6
Last executed input:

[1,2]

Status: Time Limit Exceeded

先根遍历嘛,这也能超时,wcnm,why?


struct TreeNode {
	int val;
	TreeNode *left;
	TreeNode *right;
	TreeNode(int x) : val(x), left(NULL), right(NULL) {}
	
};

class Solution {
	TreeNode*pre;
	void preorderTraversal(TreeNode* root) {
		if (root == NULL)
			return;
		vector<TreeNode*>que;
		que.push_back(root);
		while (!que.empty())
		{
			TreeNode*n = que.back();
			que.pop_back();
			if (n->right != NULL)
				que.push_back(n->right);
			if (n->left != NULL)
				que.push_back(n->left);
			if (pre == NULL)
			{
				pre = n;
				pre->left = NULL;
			}
			else
			{
				pre->right = n;
				n->left = pre;
				pre = pre->right;
			}
		}
		pre->right = NULL;
	}
public:
	void flatten(TreeNode* root) {
		clock_t start, finish;
		double Total_time;
		start = clock();
		pre = NULL;
	    preorderTraversal(root);
		
		finish = clock();
		Total_time = (double)(finish - start) / CLOCKS_PER_SEC;
		printf("%f seconds\n", Total_time);
	}
};


搞明白了,转化成单向链表,左指针都为NULL,改一下就行了,坑爹!!!

改完accept

你可能感兴趣的:(LeetCode)