• 144. Binary Tree Preorder Traversal java solutions


    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?

    Subscribe to see which companies asked this question

     1 /**
     2  * Definition for a binary tree node.
     3  * public class TreeNode {
     4  *     int val;
     5  *     TreeNode left;
     6  *     TreeNode right;
     7  *     TreeNode(int x) { val = x; }
     8  * }
     9  */
    10 public class Solution {
    11     public List<Integer> preorderTraversal(TreeNode root) {
    12         ArrayList<Integer> anslist = new ArrayList<Integer>();
    13         if(root == null) return anslist;
    14         Stack<TreeNode> s = new Stack<TreeNode>();
    15         s.push(root);
    16         while(!s.empty()){
    17             TreeNode n = s.pop();
    18             anslist.add(n.val);
    19             if(n.right != null) s.push(n.right);
    20             if(n.left != null) s.push(n.left);
    21         }
    22         return anslist;
    23     }
    24 }

    使用栈来模拟先序遍历。 递归的方法很简单,这里就不写了。

  • 相关阅读:
    part17 一些知识总结
    part16 php面向对象
    part15 php函数
    part14 php foreach循环
    part13 数组排序
    part12 php数组
    part11 php条件语句
    part10 php运算符
    part09 php字符串变量
    part08 php常量
  • 原文地址:https://www.cnblogs.com/guoguolan/p/5607877.html
Copyright © 2020-2023  润新知