首页 > 代码库 > Flatten Binary Tree to Linked List
Flatten Binary Tree to Linked List
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
这道题,先先序遍历整棵树,在遍历的时候,构造一棵只有右子树的树。将root指向这颗新生成的树即可。
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 TreeNode newTree = null;12 13 public void flatten(TreeNode root) {14 if(null == root)15 return;16 preOrder(root);17 root.right = newTree.right;18 root.left = null;19 }20 21 /**22 * 前序遍历一棵树,生成一棵只有右子树的树23 * @param root24 * @return25 */26 public void preOrder(TreeNode root){27 if(null != root){28 if(newTree == null){ //新树的根节点如果为空29 newTree = new TreeNode(root.val);30 } 31 else{ //根节点不为空32 TreeNode temp = newTree;33 34 while(temp.right != null)35 temp = temp.right; //找到插入点36 temp.right = new TreeNode(root.val); //在右子树插入结点 37 }38 preOrder(root.left); //遍历左子树39 preOrder(root.right); //遍历右子树40 }41 }42 }
Flatten Binary Tree to Linked List
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。