LeetCode:114二叉树展开为链表

java 复制代码
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public void flatten(TreeNode root) {
        TreeNode curr = root;

        while(curr != null){
            //只有左子树存在的时候才需要移接
            if(curr.left != null){
                //在左子树中找最右下角节点
                TreeNode pre = curr.left;
                while(pre.right != null){
                    pre = pre.right;
                }

                pre.right = curr.right;

                curr.right = curr.left;
                curr.left = null;
            }
            curr = curr.right;
        }
    }
}

做的过程中对照代码画图更好理解。

相关推荐
文丑颜不良啊12 分钟前
LeetCode2221~2240题目解析
java·leetcode
秋饼26 分钟前
Computer Use Agent Java 落地实战:感知-行动循环、执行器与安全围栏生产级实现
java·ai·技术分享·后端开发
Navigator_Z35 分钟前
LeetCode //C - 1317. Convert Integer to the Sum of Two No-Zero Integers
c语言·算法·leetcode
D e re k ZH1 小时前
C++ 标准库算法全景指南
数据结构·c++·算法
冻柠檬飞冰走茶2 小时前
字母移动游戏题解:贪心求最长可保留连续子串(附 C 实现)
c语言·开发语言·数据结构·算法·动态规划
文丑颜不良啊2 小时前
LeetCode2161~2180题目解析
java·leetcode
FRing032 小时前
vue2干货总结7(自定义指令、插槽、单页应用程序、路由的使用(VueRouter))
开发语言·前端·vue.js·vue2
雪落漂泊2 小时前
C++算法 二分查找篇(上)
开发语言·c++·算法
波力海苔夹心脆6753 小时前
C# WPF 资源字典详解:ResourceDictionary、MergedDictionaries 与自定义控件案例
开发语言·c#·wpf·入门教程·resource·资源字典