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

    class Solution {
    public:
        //目的是将binary tree变成前序遍历的list,但是变换过程是后序遍历
        void flatten(TreeNode *root, TreeNode *&first, TreeNode *&last){
            if (!root)
                return ;
    
            TreeNode *leftFirst = NULL;
            TreeNode *leftLast = NULL;
            TreeNode *rightFirst = NULL;
            TreeNode *rightLast = NULL;
            flatten(root->left, leftFirst, leftLast);        //对于向下调用问题,递归的先处理子树
            flatten(root->right, rightFirst, rightLast);    //对于向下调用问题,递归的先处理子树
    
            first = root;                                    //对于向上返回问题,first肯定是root
            if (root->right)                                //如果有右子树
                last = rightLast;
            else if (root->left)                            //没有右子树但是有左子树
                last = leftLast;
            else                                            //没有子树
                last = root;
    
            root->left = NULL;
            if (leftFirst && !rightFirst){
                root->right = leftFirst;
            }
            else if (!leftFirst && rightFirst){
                root->right = rightFirst;
            }
            else if (leftFirst && rightFirst){
                root->right = leftFirst;
                leftLast->right = rightFirst;
            }
            else{
                root->right = NULL;
            }
        }
    
        void flatten(TreeNode *root) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
            if (!root)
                return ;
    
            TreeNode *first;
            TreeNode *last;
            flatten(root, first, last);
    
        }
    };

    EOF

  • 相关阅读:
    .NET实现Excel文件的读写 未测试
    权限管理设计
    struts1中配置应用
    POJ 2139 Six Degrees of Cowvin Bacon(floyd)
    POJ 1751 Highways
    POJ 1698 Alice's Chance
    POJ 1018 Communication System
    POJ 1050 To the Max
    POJ 1002 4873279
    POJ 3084 Panic Room
  • 原文地址:https://www.cnblogs.com/lihaozy/p/2840398.html
Copyright © 2011-2022 走看看