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

Hints:
If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.


分析如下:

因为最后flatten的结果是树的前序遍历的结果,所以考虑一边进行前序遍历,一边进行flatten转化.


代码如下:

//48ms过大集合
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    void flatten(TreeNode *root) {
        if(root==NULL)
            return;
        stack<TreeNode*> node_stack;
        node_stack.push(root);
        TreeNode* new_root=NULL;
        TreeNode* cur=NULL;
        TreeNode* next=NULL;
        while(!node_stack.empty()){
            cur=node_stack.top();
            node_stack.pop();
            if(cur->right!=NULL)
                node_stack.push(cur->right);
            if(cur->left!=NULL)
                node_stack.push(cur->left);
            if(new_root==NULL){
                new_root=cur;
                next=cur;
                cur->left=NULL;
            } else {
                next->right=cur;
                next->left=NULL;
                next=cur;
            }
        }
        root=new_root;
    }
};

小结:

(1) 逻辑很重要,在while循环体中,应该先把cur->right, cur->left压栈,再去进行flatten。如果颠倒了顺序,就会在flatten时破坏一些还没有被处理的节点,这些节点被压栈,随后就会发生错误。


你可能感兴趣的:(LeetCode,树)