zoukankan      html  css  js  c++  java
  • 114. Flatten Binary Tree to Linked List

    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

    Approach #1: C++.

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        void flatten(TreeNode* root) {
            while (root) {
                if (root->left && root->right) {
                    TreeNode* t = root->left;
                    while (t->right)
                        t = t->right;
                    t->right = root->right;
                }
                
                if (root->left)
                    root->right = root->left;
                root->left = NULL;
                root = root->right;
            }
        }
    };
    

      

    Approach #2: Java.

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

      

    Approach #3: Python.

    # Definition for a binary tree node.
    # class TreeNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution(object):
        prev = None
        def flatten(self, root):
            """
            :type root: TreeNode
            :rtype: void Do not return anything, modify root in-place instead.
            """
            if not root:
                return 
            self.prev = root
            self.flatten(root.left)
            
            temp = root.right
            root.right, root.left = root.left, None
            self.prev.right = temp
            
            self.flatten(temp)
    

      

    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    为什么叫"鲁棒"图
    Linux系统信息查看命令......
    網頁配色工具
    java基础方面知识点
    網頁設計收藏站70個
    bj_linux...
    工具
    软件工程阅读(中英文对照)之软件维护
    软件工程新方法和技术简介(英文)
    软件工程阅读(中英文对照)之文档技术
  • 原文地址:https://www.cnblogs.com/h-hkai/p/10094984.html
Copyright © 2011-2022 走看看