二叉树展开为链表

68 阅读1分钟

LeetCode 114

leetcode-cn.com/problems/fl…

解题思路

1
/ \
2   5
/ \   \
3   4   6

//将 1 的左子树插入到右子树的地方
1
 \
  2         5
 / \         \
3   4         6        
//将原来的右子树接到左子树的最右边节点
1
 \
  2          
 / \          
3   4  
     \
      5
       \
        6
        
//将 2 的左子树插入到右子树的地方
1
 \
  2          
   \          
    3       4  
             \
              5
               \
                6   
    
//将原来的右子树接到左子树的最右边节点
1
 \
  2          
   \          
    3      
     \
      4  
       \
        5
         \
          6  

代码实现

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
	public void flatten(TreeNode root) {
		if (root == null) {
			return;
		}
		// 将左子树展开为单链表
		flatten(root.left);
		// 将右子树展开为单链表
		flatten(root.right);
		// 暂存右子树
		TreeNode temp = root.right;
		// 左子树接到根的右侧
		root.right = root.left;
		// 左子树置空
		root.left = null;
		// 再接上右子树
		while (root.right != null) {	// 移动当前根节点,直到右子树最后一个
			root = root.right;
		}
		root.right = temp;				// 再接上右子树
	}
}