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;
        }
    }
    思路:非递归的前序遍历
查看全文
  • 相关阅读:
    【证明】—— 二叉树的相关证明
    ubuntu编译安装opencv
    【换句话说】【等价描述】—— 定义及概念的不同描述
    YOLOv3训练自己的数据
    【证明】【一题多解】布尔不等式(union bound)的证明
    机器视觉:MobileNet 和 ShuffleNet
    keras图像风格迁移
    【算法导论】【排序】—— 计数排序(counting sort)
    【等价转换】—— min/max 的转换与互相转换
    卷积神经网络特征图可视化(自定义网络和VGG网络)
  • 原文地址:https://www.cnblogs.com/ldxsuanfa/p/10896050.html
  • Copyright © 2011-2022 走看看