zoukankan      html  css  js  c++  java
  • Leetcode 114. 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


    /**
     * 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) {
           TreeNode *pre = nullptr; //记住前一结点
           helper(root,pre);        //前序遍历
        }
        void helper(TreeNode *root, TreeNode *&pre) // 注意这里是一个指针的引用,pre是全局变量,不断变化
        {
            if (root == nullptr) return;
            if (pre != nullptr)
            {
                pre -> left = nullptr; // 将前一结点的左指针置空
                pre -> right = root;   // 将前一结点的右指针指向当前的根节点
            }
            pre = root;
            TreeNode *left = root -> left;
            TreeNode *right = root -> right;
            if (left != nullptr)   // 对左子树进行遍历
                helper(left,pre);  
            if (right != nullptr)  // 对右子树进行遍历
                helper(right,pre);
        }
    };
  • 相关阅读:
    Thread与Handler
    开始机顶盒的生涯
    解决布局被键盘顶的难题
    自动滚动的Textview
    2-解决粘包问题
    1-socket编程
    zipfile模块
    subprocess模块
    day31-异常处理
    collections模块
  • 原文地址:https://www.cnblogs.com/simplepaul/p/6733791.html
Copyright © 2011-2022 走看看