114. Flatten Binary Tree to Linked List (Stack, Tree; DFS)

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

法I:递归,前序遍历

/**
 * 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:
    void flatten(TreeNode* root) {
        if(!root) return;
        else preOrderTraverse(root);
    }
    
    TreeNode* preOrderTraverse(TreeNode* root){
        TreeNode* rightHead = root->right; //save root->right
        TreeNode* tail;
        
        if(!root->left && !rightHead){
            return root;
        }
        if(root->left) { //have left child
            root->right = root->left;
            root->left = NULL;
            tail = preOrderTraverse(root->right);
            if(rightHead){ //have both left child and right child
                tail->right = rightHead; //如果left==NULL, 这里就不能使用tail->right,所以得分开讨论有右子树情况 
                tail = preOrderTraverse(rightHead);
            }
        }
        else{ //only have right child
            tail = preOrderTraverse(rightHead);
        }
        
        return tail;
    }
};

 法II:迭代

每次循环,找到左子树前序遍历的最后一个节点(即最右的叶子节点),把右节点作为它的右儿子,当前节点的右儿子置为左节点,左节点置为NULL。

然后把当前节点挪到它的右儿子,进入下一次循环

/**
 * 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;
        TreeNode *cur = root, *tail = NULL;
        while (cur != NULL) {
            if (cur->left != NULL) {
                tail = cur->left;
                while (tail->right) tail = tail->right;
                tail->right = cur->right;
                cur->right = cur->left;
                cur->left = NULL;
            }
            cur = cur->right;
        }
    }
};

 

posted on 2015-10-03 17:27  joannae  阅读(178)  评论(0编辑  收藏  举报

导航