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

    一、题目

      1、审题

      2、分析

        给出一棵二叉树,按照先序遍历顺序组成一棵斜右二叉树。

    二、解答

      1、思路:

        方法一、 

          采用一个栈进行先序遍历,遍历时将节点重新组装。

    public void flatten(TreeNode root) {
            Stack<TreeNode> stack = new Stack<TreeNode>();
            if(root == null)
                return;
            stack.add(root);
            TreeNode tmpNode = root;
            
            while(!stack.isEmpty()) {
                
                TreeNode node = stack.pop();
                
                if(node.right != null)
                    stack.add(node.right);
                
                if(node.left != null)
                    stack.add(node.left);
                
                if(node != root) {
                    tmpNode.right = node;
                    tmpNode.left = null;
                    tmpNode = node;
                }
            }
        }

      

      方法二、

        采用递归

        递归实现 右-->左-->根 遍历,并拼接原二叉树的节点顺序。

       private TreeNode prev = null;
        public void flatten(TreeNode root) {
            if(root == null)
                return;
            
            flatten(root.right);
            flatten(root.left);
            
            root.right = prev;
            root.left = null;
            prev = root;
        }

      方法三、

        采用 Morris Traversal 方法线索二叉树。

        线索二叉树,利用叶子节点中的空闲指针指向中序遍历的后续一个节点。

        性能较好,O(1)空间复杂度

        public void flatten3(TreeNode root) {
            
            TreeNode cur = root;
            TreeNode pre = root;
            
            while(cur != null) {
                
                if(cur.left == null) {
                    cur = cur.right;
                }
                else {
                    pre = cur.left;
                    while(pre.right != null && pre.right != cur)
                        pre = pre.right;
                    
                    if(pre.right == null) {
                        pre.right = cur;
                        cur = cur.left;
                    }
                    else {
                        TreeNode right = cur.right;
                        cur.right = cur.left;
                        cur.left = null;
                        pre.right = right;
                        cur = right;
                    }
                }
            }
        }
  • 相关阅读:
    web 学习资源整理
    CodeSmith 学习资料收集
    常用 T_SQL 语句
    SQL Server 2000查询分析器自定义查询快捷键
    插入标识列 identity_insert
    c# 上传FTP文件
    (.Net 3.5Sp1)WebForm使用System.Web.Routing
    SPQuery.ViewAttributes
    ChatterBot之linux下安装mongodb 02
    linux端口开放指定端口的两种方法
  • 原文地址:https://www.cnblogs.com/skillking/p/9743605.html
Copyright © 2011-2022 走看看