114. Flatten Binary Tree to Linked List【Medium】【将给定的二叉树转化为“只有右孩子节点”的链表(树)】

Given a binary tree, flatten it to a linked list in-place.

For example, given the following tree:

    1
   / \
  2   5
 / \   \
3   4   6

The flattened tree should look like:

1
 \
  2
   \
    3
     \
      4
       \
        5
         \
          6
Accepted
218,918
Submissions
533,947

【解析】由上图可知,如果右子树不为空,则右子树最后肯定为左子树最有一个靠右的孩子节点的右子树,而左子树最后成为整棵树的右子树。这样,首先判断左子树是否为空,不为空就寻找到树根的左孩子节点,然后寻找该节点是否有右孩子,如果有继续寻找,直到找到属于叶子节点的右孩子,此时,该节点的右子树“指向”当前树的右子树,并将当前左子树变为树根的右孩子,将整棵树左孩子置为空。最后,根节点“指向”根节点的右孩子,继续上述操作,直到整棵树遍历完即得到结果。

1.首先,将根节点的右子树,连接到根节点的左子树的最右节点,如下图所示:

2.然后将左子树移动到右边,如下图所示:

3.之后,将根节点的右节点 作为 当前的根节点,循环进行。

                              

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public void flatten(TreeNode root) {
        while(root != null) {
            if(root.left != null) {
                TreeNode pre = root.left;
                while(pre.right != null) {
                    pre = pre.right;
                }
                pre.right = root.right;
                root.right = root.left;
                root.left = null;
            }
            root = root.right;
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/Roni-i/p/10434572.html