11
08/2015
[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 6The 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.
解题思路:
题意为将二叉树按照先序遍历压平。最开始时对in-place理解错误,以为空间复杂度只能为O(1)。其实不然(我们姑且认为递归的时候空间不变)。
我们可以用递归来解决这个问题。
首先定义个递归函数,改递归函数返回root为根节点的最右节点。
倘若root->left不为空,则将左子树的节点插入到root->right中。
递归代码如下:
/** * 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) { flattenHelper(root); } //返回root为根的最右边的那个节点 TreeNode* flattenHelper(TreeNode* root){ if(root == NULL){ return NULL; } TreeNode* leftMost = flattenHelper(root->left); TreeNode* rightMost = flattenHelper(root->right); if(leftMost!=NULL){ TreeNode* temp = root->right; root->right = root->left; root->left = NULL; leftMost->right = temp; } if(leftMost==NULL&&rightMost==NULL){ return root; }else if(rightMost==NULL){ return leftMost; }else{ return rightMost; } } };
0 条评论