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

    Given a binary tree, flatten it to a linked list in-place.
    For example,
    Given
    1
    /
    2 5
    /
    3 4 6
    The flattened tree should look like:
    1

    2

    3

    4

    5

    6
    Hints:
    If you notice carefully in the flattened tree, each node's right child points to the next node
    of a pre-order traversal.

    Solution: Recursion. Return the last element of the flattened sub-tree.

     1 /**
     2  * Definition for binary tree
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     void flatten(TreeNode *root) {
    13         TreeNode* end = NULL;
    14         flattenRe(root, end);
    15     }
    16     
    17     void flattenRe(TreeNode* root, TreeNode* &end)
    18     {
    19         if(!root) return;
    20         TreeNode* lend = NULL;
    21         TreeNode* rend = NULL;
    22         flattenRe(root->left, lend);
    23         flattenRe(root->right, rend);
    24         if(root->left) {
    25             lend->right = root->right;
    26             root->right = root->left;
    27             root->left = NULL;
    28         }
    29         end = rend ? rend : (lend ? lend : root);
    30     }
    31 };
  • 相关阅读:
    php 微信调用扫一扫
    JavaSE常用API
    Java中的异常处理
    Java实现多态的机制是什么?
    JavaSE(下)
    JavaSE语法(中)
    JavaSE语法
    Java面向对象
    Java零基础入门之常用工具
    Java抽象类、接口、内部类
  • 原文地址:https://www.cnblogs.com/zhengjiankang/p/3676162.html
Copyright © 2011-2022 走看看