Leetcode之Flatten Binary Tree to Linked List

题目:

Given a binary tree, flatten it to a linked list in-place.

For example, given the following tree:

    1
   / \
  2   5
 / \   \
3   4   6

The flattened tree should look like:

1
 \
  2
   \
    3
     \
      4
       \
        5
         \
          6

代码:

class Solution {
public:
TreeNode* helper(TreeNode* root) {

	if (!root)return NULL;
	if (!root->left && !root->right)return root;
	if (!root->left) return helper(root->right);
	if (!root->right) {
		TreeNode* temp1 = helper(root->left);
		root->right = root->left;
		root->left = NULL;
		return temp1;
	}
	TreeNode* temp1 = helper(root->left);
	TreeNode* temp2=helper(root->right);
	temp1->right = root->right;
	root->right = root->left;
	root->left = NULL;

	return temp2;
}
void flatten(TreeNode* root) {
	helper(root);
}
};

想法:

考虑全面!

猜你喜欢

转载自blog.csdn.net/qq_35455503/article/details/91493985