其他分享
首页 > 其他分享> > 二叉树展开为链表

二叉树展开为链表

作者:互联网

/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     public $val = null;
 *     public $left = null;
 *     public $right = null;
 *     function __construct($val = 0, $left = null, $right = null) {
 *         $this->val = $val;
 *         $this->left = $left;
 *         $this->right = $right;
 *     }
 * }
 */
class Solution {

    /**
     * @param TreeNode $root
     * @return NULL
     */
    function flatten($root)
    {
        return $this->flattenAndReturn($root);
    }
    
    public function flattenAndReturn(&$root)
    {
        if (empty($root)) {
            return null;
        }
        $leftLast = $this->flattenAndReturn($root->left);
        $rightLast = $this->flattenAndReturn($root->right);
        if (!empty($leftLast)) {
            $leftLast->right = $root->right;
            $root->right = $root->left;
            $root->left = null;
        }
        return $rightLast ? $rightLast : ($leftLast ? $leftLast : $root);
    }
}

标签:right,return,leftLast,链表,二叉树,null,root,展开,left
来源: https://blog.csdn.net/qq_40192867/article/details/123250811