码迷,mamicode.com
首页 > 其他好文 > 详细

leetCode(42):Flatten Binary Tree to Linked List

时间:2015-07-17 22:51:18      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:

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

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


/**
 * 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 == NULL)
    		return;
    	TreeNode* rightNode = root->right;//保存右孩子
    	TreeNode* tmp = root->left;
    	while (tmp && tmp->right)
    	{
    		tmp = tmp->right;
    	}//找到右子的直接前驱
    		
    	if (tmp)//如果左孩子不为空
    	{
    		tmp->right = rightNode;//让直接前驱指向保存的右孩子
    		root->right = root->left;//右指针指向左孩子
    		root->left = NULL;//左指针指向空
    		flatten(root->right);//对左孩子作同样的处理
    	}
    	flatten(rightNode);//对右孩子作同样的处理
    }
};



版权声明:本文为博主原创文章,未经博主允许不得转载。

leetCode(42):Flatten Binary Tree to Linked List

标签:

原文地址:http://blog.csdn.net/walker19900515/article/details/46931131

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!