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

    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].

    Note: Recursive solution is trivial, could you do it iteratively?

    /**
     * Definition for binary tree
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public ArrayList<Integer> preorderTraversal(TreeNode root) {
             ArrayList<Integer> result = new ArrayList<Integer>();
            if(root != null){
                Stack<TreeNode> sta = new Stack<TreeNode>();
                sta.push(root);
                while(!sta.empty()){
                    TreeNode aNode = sta.pop();
                    if(aNode.right != null)
                        sta.push(aNode.right);
                    if(aNode.left != null)
                        sta.push(aNode.left);
                    result.add(aNode.val);
                }
            }
            return result;
        }
    }
    

      

  • 相关阅读:
    IfcQuantityWeight
    IfcPhysicalComplexQuantity
    IfcBinary
    大服务器
    DFF环境配置
    Java程序设置为开机自启动
    IfcArbitraryProfileDefWithVoids
    定位日志
    blazor相关资料
    老人与海 电影
  • 原文地址:https://www.cnblogs.com/averillzheng/p/3553003.html
Copyright © 2011-2022 走看看