[Leetcode]Flatten Binary Tree to Linked List~

来源:互联网 发布:acrobat for mac安装 编辑:程序博客网 时间:2024/06/05 09:59

Flatten Binary Tree to Linked List My Submissions Question
Total Accepted: 66064 Total Submissions: 223714 Difficulty: Medium
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

click to show hints.

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

Subscribe to see which companies asked this question
中午上课前在leetcode做的时候出了各种细节错误,于是上课的时候在纸上写了下,也就十多分钟。上完课我回来提交,AC。
有时候在纸上写会更细心,写的过程也在思考。
思路:
递归处理,将左右子树Flatten,并判断左子树是否为空,为空则直接返回。不为空则将左子树的最后一个结点的右孩子设为右子树,并将左子树设置为根结点的右子树,并清空根节点左子树即可

/** * 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)   return;        if(!root->left && !root->right) return;        flatten(root->left);        flatten(root->right);        if(end(root->left)){            end(root->left) -> right = root->right;            root->right = root->left;            root->left = nullptr;            return;        }        else{            return;        }    }    TreeNode* end(TreeNode* root){        if(!root)   return nullptr;        auto p = root;        while(p->right){            p = p->right;        }        return p;    }};

P.S 上张图记录下,这种感觉蛮好的
这里写图片描述

0 0
原创粉丝点击