zoukankan      html  css  js  c++  java
  • 0114. Flatten Binary Tree to Linked List (M)

    Flatten Binary Tree to Linked List (M)

    题目

    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
    

    题意

    将一个二叉树的结构变为只有右子树的一直链,且顺序为原二叉树的前序遍历。

    思路

    方法有点像 Morris Traversal:如果当前结点root存在左子树,则将该结点的右子树接在其左子树最右结点的右边,再将root的左子树变为右子树,令 root = root.right 重复上述操作。


    代码实现

    Java

    class Solution {
        public void flatten(TreeNode root) {
            while (root != null) {
                if (root.left != null) {
                    TreeNode x = root.left;
                    while (x.right != null) {
                        x = x.right;
                    }
                    x.right = root.right;
                    root.right = root.left;
                    root.left = null;
                }
                root = root.right;
            }
        }
    }
    

    JavaScript

    /**
     * @param {TreeNode} root
     * @return {void} Do not return anything, modify root in-place instead.
     */
    var flatten = function (root) {
      while (root) {
        if (root.left) {
          let tmp = root.left
          while (tmp.right) tmp = tmp.right
          tmp.right = root.right
          root.right = root.left
          root.left = null
        }
        root = root.right
      }
    }
    
  • 相关阅读:
    76. 最小覆盖子串 (JAVA)
    95. 不同的二叉搜索树 II (Java)
    HTTP/HTTPS协议 & GraphQL(非RESTFUL方式)
    Round Robin
    94. Binary Tree Inorder Traversal (Java)
    90. Subsets II (Java)
    Notepad++ 连接 FTP 实现编辑 Linux文件
    Git
    根据进程ID查找运行程序目录
    Flink 的广播变量
  • 原文地址:https://www.cnblogs.com/mapoos/p/14771533.html
Copyright © 2011-2022 走看看