114. Flatten Binary Tree to Linked List

网友投稿 696 2022-09-04

114. Flatten Binary Tree to Linked List

114. Flatten Binary Tree to Linked List

Given a binary tree, flatten it to a linked list in-place.

For example, Given

1 / \ 2 5 / \ \ 3 4 6

The flattened tree should look like:

1 \ 2 \ 3 \ 4 \ 5 \ 6

click to show hints.

/** * 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) return; TreeNode temp = root; TreeNode current = root; while(current!=null){ if(current.left!=null){ temp = current.left; while(temp.right!=null) temp = temp.right; temp.right = current.right; current.right = current.left; current.left = null; } current = current.right; } }}

/** * 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) return; TreeNode r = new TreeNode(0); // the first element is a place holder fl(root, r); root.left = null; if (r.right != null) root.right = r.right.right; } private TreeNode fl(TreeNode node, TreeNode result) { if (node == null) return result; result.right = new TreeNode(node.val); return fl(node.right, fl(node.left, result.right)); }}

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:在服务器上对 PHP-FPM 和 Nginx 进行安装配置详解
下一篇:152. Maximum Product Subarray
相关文章

 发表评论

暂时没有评论,来抢沙发吧~