首页 > 代码库 > leetcode 之 Flatten Binary Tree to Linked List

leetcode 之 Flatten Binary Tree to Linked List

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

思路:对二叉树进行先序遍历,把左子树为空的节点的左子树指向它的后序节点,然后把所有的右子树指向左子树

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

void flatten(TreeNode *root)
{
	if(!root || (!root->left && !root->right))return;
	TreeNode* pre = NULL,*p = root;
	stack<TreeNode*> stk;
	while (p || !stk.empty())//先序遍历
	{
		while (p)
		{
			stk.push(p);
			p = p ->left;
		}
		p = stk.top();
		stk.pop();
		if(!p ->left)pre = p;
		p = p->right;
		if(p)pre->left = p;
	}
	p = root;
	while (p)
	{
		p->right = p->left;
		p->left = NULL;
		p = p->right;
	}
}

剑指offer之把二元查找树转化成排序的双向链表

题目:输入一棵二元查找树,将该二元查找树转换成一个排序的双向链表。要求不能创建任何新的结点,只调整指针的指向。

分析:我们可以中序遍历整棵树。按照这个方式遍历树,比较小的结点先访问。如果我们每访问一个结点,假设之前访问过的结点已经调整成一个排序双向链表,我们再把调整当前结点的指针将其链接到链表的末尾。当所有结点都访问过之后,整棵树也就转换成一个排序双向链表了

TreeNode* convertTreeToDoubleList(TreeNode* root,TreeNode* &lastNode)
{
	if(!root)return root;
	TreeNode* curNode = root;
	TreeNode* head = convertTreeToDoubleList(root->left,lastNode);//把左子树转换好,并获得头结点和尾节点

	curNode ->left = lastNode;//指向左子树的尾节点
	if(lastNode)lastNode->right = curNode;//左子树的尾节点指向根节点
	lastNode = curNode;//当前的尾节点
	if(!head)head = curNode;

	TreeNode* lHead  = convertTreeToDoubleList(root->right,lastNode);//把右子树转换好,并获得头结点和尾节点
	curNode->right  = lHead;
	if(lHead)lHead->left = curNode;

	return head;
}

TreeNode* convertTreeToDoubleList(TreeNode* root)
{
	TreeNode* lastNode = NULL;
	return convertTreeToDoubleList(root,lastNode);
}


leetcode 之 Flatten Binary Tree to Linked List