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;
        }
    }
    思路:非递归的前序遍历
查看全文
  • 相关阅读:
    公钥,私钥和数字签名这样最好理解
    SolrCloud的官方配置方式
    由于Windows和Linux行尾标识引起脚本无法运行的解决
    python模块名和文件名冲突解决
    Linux下编译安装python3
    Storm集群的安装配置
    Linux下编译安装Apache 2.4
    SELinux的关闭与开启
    Spring MVC配置静态资源的正常访问
    SolrCloud环境配置
  • 原文地址:https://www.cnblogs.com/ldxsuanfa/p/10896050.html
  • Copyright © 2011-2022 走看看