题目:Flatten Binary Tree to Linked List
<span style="font-size:18px;">/**LeetCode Flatten Binary Tree to Linked List * 题意:给定一个二叉树,将其转变为一个相当于单链表的结构,观察可知该结构即:每一个节点左儿子为空,右儿子指向自己先序遍历时的下一个节点 * 思路:有观察可得,应对其进行先序遍历,得到正确的序列连接起来 * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ package javaTrain; public class Train18 { public void flatten(TreeNode root) { if(root== null || (root.left == null && root.right == null)) return; preOrder(root); return; } private TreeNode preOrder(TreeNode root){ if(root== null || (root.left == null && root.right == null)) return root; TreeNode left = root.left; TreeNode right = root.right; TreeNode last; root.left = null; if(left != null){ root.right = left; last = preOrder(left); last.left = null; if(right != null){ last.right = right; return preOrder(right); } else return last; } else{ root.right = right; return preOrder(right); } } } </span>
时间: 2024-08-02 02:51:46