LeetCode题目-114

首页 编程分享 LEET_CODE 正文

leetCode 转载 编程分享 2016-06-26 17:52:30

简介 LeetCode题目-114


✏Leetcode基础刷题之(114. Flatten Binary Tree to Linked List)


✏描述

给定一棵二叉树,把二叉树展开平铺成一个单链表(其实还是一棵树,只是节点都是右子树)。


✏题目实例

✏题目分析

利用深度优先搜索找到最左子节点,然后定位到当前节点的父节点,把最左节点赋值给父节点的右子节点,然后再把原来的右子节点变成新的右子节点的右子节点,然后退回到上一层父子节点,重复这个操作。

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

    /**
     * @param TreeNode $root
     * @return NULL
     */
    function flatten($root) {
        if(!$root) return ;
        if($root->left) $this->flatten($root->left);
        if($root->right) $this->flatten($root->right);
        $node=$root->right;
        $root->right=$root->left;
        $root->left=null;
        while($root->right) $root=$root->right;
        $root->right=$node;
    }
}

转载链接:https://leetcode.cn/


Tags:


本篇评论 —— 揽流光,涤眉霜,清露烈酒一口话苍茫。


    声明:参照站内规则,不文明言论将会删除,谢谢合作。


      最新评论




ABOUT ME

Blogger:袅袅牧童 | Arkin

Ido:PHP攻城狮

WeChat:nnmutong

Email:nnmutong@icloud.com

标签云