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

    Link: http://oj.leetcode.com/problems/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?

    Recursion version:

     1 /**
     2  * Definition for binary tree
     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     ArrayList<Integer> nodes = new ArrayList<Integer>();
    12 
    13     public ArrayList<Integer> preorderTraversal(TreeNode root) {
    14 
    15         preorderTraversal_recursion(root);
    16         return nodes;
    17     }
    18     public void preorderTraversal_recursion(TreeNode root){
    19         if(root==null)
    20             return;
    21         nodes.add(root.val);
    22         preorderTraversal_recursion(root.left);
    23         preorderTraversal_recursion(root.right);
    24 
    25     }
    26 }

    Iteration version:

     1 /**
     2  * Definition for binary tree
     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 ArrayList<Integer> preorderTraversal(TreeNode root) {
    12     ArrayList<Integer> nodes = new ArrayList<Integer>();
    13         if (root == null)
    14             return nodes;
    15         Stack<TreeNode> stack = new Stack<TreeNode>();
    16         // this is used to identify the node pop from stack
    17         TreeNode node;
    18         stack.push(root);
    19         while (!stack.isEmpty()) {
    20             node = stack.pop();
    21             nodes.add(node.val);
    22             if (node.right != null)
    23                 stack.push(node.right);
    24             if (node.left != null)
    25                 stack.push(node.left);
    26         }
    27         return nodes;
    28     }
    29 }
  • 相关阅读:
    几个简单递归js 实现
    js中阻止事件冒泡
    判断是否IE 最酷的代码
    C# Hashtable 读取 key 和 value
    ubuntu搭建jdk+jenkins
    Shell逻辑运算符及表达式
    Linux命令的返回值
    python调用c/c++时传递结构体参数
    Git错误总结
    Bash Shell中命令行选项/参数处理
  • 原文地址:https://www.cnblogs.com/Altaszzz/p/3705682.html
Copyright © 2011-2022 走看看