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

    题目:将一棵二叉树履平成一个类似Linked-list的东西。

    思路:该过程类似于二叉树的前序遍历,但是遍历代码,我处理不来参数的变化。没AC。

    -------->写的很好的解题博客

    参考上述博客,思路很清楚的写出代码:

     1  public void flatten(TreeNode root) {
     2         if(root == null) return;
     3         
     4         if(root.left != null){
     5             TreeNode leftNode = root.left;
     6             TreeNode rightNode = root.right;
     7             root.left = null;
     8             root.right = leftNode;
     9             
    10             while(leftNode.right != null) leftNode = leftNode.right;
    11             leftNode.right = rightNode;
    12         }
    13         
    14         flatten(root.right);
    15         
    16  }

    采用前序遍历错误的代码:留在下方,回头来改正:

     1    public void flatten(TreeNode root) {
     2         if(root == null) return;
     3         
     4         TreeNode newRoot = null , head = null;
     5         Stack<TreeNode> s = new Stack<TreeNode>();
     6         
     7         while(root != null || !s.isEmpty()){
     8             while(root != null){
     9                 
    10                 //visit node
    11                 if(newRoot == null) {
    12                     newRoot = new TreeNode(root.val);
    13                     head = newRoot;
    14                 }else{
    15                     newRoot.right = new TreeNode(root.val);
    16                     newRoot = newRoot.right;
    17                 }
    18                 
    19                 s.push(root);
    20                 
    21                 //visit leftChild
    22                 root = root.left;
    23             }
    24             if(!s.isEmpty()){
    25                 
    26                 //visit rightChild
    27                 root = s.pop();
    28                 root = root.right;
    29             }
    30         }
    31         root = head;
    32     }
  • 相关阅读:
    log4j学习
    数据库索引
    php 通过exec 创建git分支失败
    Nginx 常用全局变量 及Rewrite规则详解
    Jetbrains phpstorm pycharm 免费授权注册码
    Nginx return 关键字配置小技巧
    PHP 加密 和 解密 方法
    Nginx 禁用IP IP段
    Yii2 捕获错误日志
    transform 实现响应式绝对居中
  • 原文地址:https://www.cnblogs.com/glamourousGirl/p/3770561.html
Copyright © 2011-2022 走看看