首页 > 代码库 > Flatten Binary Tree to Linked List
Flatten Binary Tree to Linked List
Note:
It is easier to use divided conquer. As you can see, the question is just to add right to left‘s last. Here we care more about last then the top because top can always be traced by root. Since the right is the last if it is null, first return right and then check left side.
/** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } */ public class Solution { /** * @param root: a TreeNode, the root of the binary tree * @return: nothing */ public void flatten(TreeNode root) { // write your code here flattenTree(root); } private TreeNode flattenTree(TreeNode root) { if (root == null) { return root; } //This problem is looking for the last element TreeNode leftLast = flattenTree(root.left); TreeNode rightLast = flattenTree(root.right); if (leftLast != null) { leftLast.right = root.right; root.right = root.left; root.left = null; } if (rightLast != null) { return rightLast; } if (leftLast != null) { return leftLast; } return root; } }
// The traverse version. Please check http://www.jiuzhang.com/solutions/flatten-binary-tree-to-linked-list/
Flatten Binary Tree to Linked List
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。