zoukankan      html  css  js  c++  java
  • [LintCode] Flatten Binary Tree to Linked List 将二叉树展开成链表

    Flatten a binary tree to a fake "linked list" in pre-order traversal.

    Here we use the right pointer in TreeNode as the next pointer in ListNode.

    Notice

    Don't forget to mark the left child of each node to null. Or you will get Time Limit Exceeded or Memory Limit Exceeded.

    Example
                  1
                   
         1          2
        /           
       2   5    =>    3
      /              
     3   4   6          4
                         
                          5
                           
                            6
    

    LeetCode上的原题,请参见我之前的博客Flatten Binary Tree to Linked List

    解法一:

    class Solution {
    public:
        /**
         * @param root: a TreeNode, the root of the binary tree
         * @return: nothing
         */
        void flatten(TreeNode *root) {
            if (!root) return;
            stack<TreeNode*> s;
            s.push(root);
            while (!s.empty()) {
                TreeNode *t = s.top(); s.pop();
                if (t->left) {
                    TreeNode *r = t->left;
                    while (r->right) r = r->right;
                    r->right = t->right;
                    t->right = t->left;
                    t->left = NULL;
                }
                if (t->right) s.push(t->right);
            }
        }
    };

    解法二:

    class Solution {
    public:
        /**
         * @param root: a TreeNode, the root of the binary tree
         * @return: nothing
         */
        void flatten(TreeNode *root) {
            if (!root) return;
            if (root->left) flatten(root->left);
            if (root->right) flatten(root->right);
            TreeNode *t = root->right;
            root->right = root->left;
            root->left = NULL;
            while (root->right) root = root->right;
            root->right = t;
        }
    };

    解法三:

    class Solution {
    public:
        /**
         * @param root: a TreeNode, the root of the binary tree
         * @return: nothing
         */
        void flatten(TreeNode *root) {
            TreeNode *cur = root;
            while (cur) {
                if (cur->left) {
                    TreeNode * t = cur->left;
                    while (t->right) t = t->right;
                    t->right = cur->right;
                    cur->right = cur->left;
                    cur->left = NULL;
                }
                cur = cur->right;
            }
        }
    };
  • 相关阅读:
    advisor调优工具优化sql(基于sql_id)
    关于等待事件cursor: pin S
    队列等待之enq: TX
    HTML5+CSS3从入门到精通 中文pdf完整版[229MB] 下载
    unity 控制透明度
    unity 限制模型移动的边界
    unity监测按下键的键值并输出+unity键值
    unity EventTrigger与模型
    wpf 获取桌面上的鼠标位置
    unity 代码更换ugui中image的关联素材
  • 原文地址:https://www.cnblogs.com/grandyang/p/5642095.html
Copyright © 2011-2022 走看看