首页 » 编程之美 » 正文

[leetcode_114]Flatten Binary Tree to Linked List

将一个二叉树扁平化。
所有扁平化就是:

     1
    / \
   2   5
  / \   \
 3   4   6

1
\
2
\
3
\
4
\
5
\
6

each node’s right child points to the next node of a pre-order traversal.

class Solution {
public:
    TreeNode * flattenStep(TreeNode *root) {
        if(root->left == NULL && root->right == NULL)
            return root;
        TreeNode * tmp = NULL;
        if(root->right != NULL)
            tmp = flattenStep(root->right);
        if(root->left != NULL)
            root->right = flattenStep(root->left);
        else
            root->right = NULL;
        root->left = NULL;
        if(tmp != NULL) {<br />
            TreeNode * tmpright = root;
            while(tmpright-&gt;right != NULL)
                tmpright = tmpright-&gt;right;
            tmpright-&gt;right = tmp;
        }
        return root;
    }
    void flatten(TreeNode *root) {
        if(root == NULL)return;
        root = flattenStep(root);
    }
};

发表评论