本文主要是介绍LeetCode 114 Flatten Binary Tree to Linked List (DFS 分治),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Given a binary tree, flatten it to a linked list in-place.
For example, given the following tree:
1/ \2 5/ \ \ 3 4 6
The flattened tree should look like:
1\2\3\4\5\6
题目链接:https://leetcode.com/problems/flatten-binary-tree-to-linked-list/
题目分析:flatten左子树,接到右边,不断递归
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode(int x) { val = x; }* }*/
class Solution {public void flatten(TreeNode root) {if (root == null || (root.left == null && root.right == null)) {return;}while (root != null) {TreeNode lTree = root.left;TreeNode rTree = root.right;flatten(lTree);// link flattened left node to root's rightroot.right = lTree;root.left = null;// go to the previous right nodewhile (root.right != null) {root = root.right;}root.right = rTree;root = root.right;}}
}
这篇关于LeetCode 114 Flatten Binary Tree to Linked List (DFS 分治)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!