leetcode15: flatten binary tree

Flatten Binary Tree to Linked ListOct 14 '12

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


/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public void flatten(TreeNode root) {
        // Start typing your Java solution below
        // DO NOT write main() function
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        
        //preorder traversal.
        Stack<TreeNode> stack = new Stack<TreeNode>();
        
        TreeNode node = root;
        
        
        while(!stack.isEmpty() || node != null) {
            if(node!=null) {
                queue.add(node);
                stack.push( node );
                node = node.left;
            } else {
                node = stack.pop();
                node = node.right;
            }
        }
        
        
        while( !queue.isEmpty() ) {
            node = queue.remove();
            node.left = null;
            node.right = queue.peek();
        }
    }
}


uncomplete

/**
 * 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) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        flattenRec( root);
        
    }
    
    TreeNode* flattenRec( TreeNode *root) {
        if(!root) return NULL;
        
        TreeNode* tail = NULL;
        if(root->left){
            tail = flattenRec(root->left);
        } else {
            tail = root;
        }
        
        TreeNode * temp = root->right;
        
        root->right = root->left;
        
        
        if(temp) {
            tail->right = temp;
            tail = flattenRec(temp);
        } 
        
        return tail;
    }
};





posted @ 2012-12-25 01:36  西施豆腐渣  阅读(109)  评论(0编辑  收藏  举报