标题: | Flatten Binary Tree to Linked List |
通过率: | 28.7% |
难度: | 中等 |
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
Hints:
If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.
本题就是把一颗树变成退化树
都是只有右孩子,那么需要操作的就是找到左孩子的最有节点,将root的右树连接到左孩子的最右节点,然后root的右孩子指向左孩子,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 public void flatten(TreeNode root) { 12 while(root!=null){ 13 if(root.left!=null){ 14 TreeNode tmp=root.left; 15 while(tmp.right!=null) 16 tmp=tmp.right; 17 tmp.right=root.right; 18 root.right=root.left; 19 root.left=null; 20 } 21 root=root.right; 22 } 23 } 24 }