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
      }
    }
    
  • 相关阅读:
    引用的难点:函数返回值是引用(引用当左值)
    引用的意义与本质
    引用做函数参数
    Uva
    Uva
    Uva
    暑假集训-8.06总结
    暑假集训-8.05总结
    CH1801( 括号画家)
    最大异或对
  • 原文地址:https://www.cnblogs.com/mapoos/p/14771533.html
Copyright © 2011-2022 走看看