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 }
  • 相关阅读:
    Iphone和iPad适配, 横竖屏
    JSONModel
    iPhone socket 编程之BSD Socket篇
    UIImageView 动画 / UIImage 方向
    iOS团队开发者测试
    xcode6以后, 使用.pch
    C# new override
    MVC, MVP, MVVM
    VS2010 VC Project的default Include设置
    centos 7 安装mysql5.6rpm格式197
  • 原文地址:https://www.cnblogs.com/Altaszzz/p/3705682.html
Copyright © 2011-2022 走看看