首页 > 代码库 > Leetcode: Flatten Binary Tree to Linked List
Leetcode: 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 6The flattened tree should look like: 1 2 3 4 5 6click to show hints.Hints:If you notice carefully in the flattened tree, each node‘s right child points to the next node of a pre-order traversal.
难度:70
把先序遍历的结果存到一个ArrayList<TreeNode>里面,然后从根节点开始,依次把左子树置空,右子树置为ArrayList里面存的下一个节点
1 /** 2 * Definition for binary tree 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */10 public class Solution {11 public void flatten(TreeNode root) {12 if (root == null) return;13 ArrayList<TreeNode> preorder = new ArrayList<TreeNode>();14 helper(root, preorder);15 preorder.remove(0);16 TreeNode temp = root;17 while (preorder.size()!=0) {18 temp.left = null;19 temp.right = preorder.get(0);20 preorder.remove(0);21 temp = temp.right;22 }23 }24 25 public void helper(TreeNode root, ArrayList<TreeNode> preorder) {26 if (root == null) return;27 preorder.add(root);28 helper(root.left, preorder);29 helper(root.right, preorder);30 }31 }
需要注意看一个arraylist是否为减为空应该是看它的size是否等于0,而不是arraylist == null,后者表示没有给该arraylist分配地址
Leetcode: Flatten Binary Tree to Linked List
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。