zoukankan      html  css  js  c++  java
  • Binary Tree Preorder Traversal

    版权声明:本文为博主原创文章,未经博主同意不得转载。 https://blog.csdn.net/dutsoft/article/details/37739285

    Given a binary tree, return the preorder traversal of its nodes' values.

    For example:
    Given binary tree {1,#,2,3},

       1
        
         2
        /
       3
    

    return [1,2,3].

    /**
     * Definition for binary tree
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
       public List<Integer> preorderTraversal(TreeNode root) {
            Stack<TreeNode> nodeStack=new Stack<TreeNode>();
            List<Integer> list=new ArrayList<Integer>();
            TreeNode node=root;
            while(!nodeStack.isEmpty() || node!=null){
                if(node!=null){
                    list.add(node.val);
                    if(node.right!=null){
                        nodeStack.add(node.right);
                    }
                    node=node.left;
                }
                else{
                	node=nodeStack.peek();
                	nodeStack.pop();
                }
            }
            return list;
        }
    }
    思路:非递归的前序遍历
查看全文
  • 相关阅读:
    学习比较-列表
    查看Linux下系统资源占用常用命令
    eclipse加载maven工程提示pom.xml无法解析org.apache.maven.plugins:maven-resources-plugin:2.4.3解决方案
    springmvc 注解扫描失败的可能原因
    单例模式:懒加载(延迟加载)和即时加载
    nginx 正向代理和反向代理
    LINUX中错误 SELinux is disabled
    修改Win10默认窗口背景色为护眼色的方法
    搜索引擎之Lucene
    MongoDB系列(一):MongoDB安装及基础语法
  • 原文地址:https://www.cnblogs.com/ldxsuanfa/p/10896050.html
  • Copyright © 2011-2022 走看看