zoukankan      html  css  js  c++  java
  • 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?

    Using Stack

    /**
     * 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)
                return result;
            Stack<TreeNode> s = new Stack<TreeNode>();
            s.add(root);
            while(!s.isEmpty()){
                TreeNode tmp = s.pop();
                result.add(tmp.val);
                if(tmp.right != null){
                    s.push(tmp.right);
                }
                if(tmp.left != null){
                    s.push(tmp.left);
                }
            }
            
            return result;
        }
    }

    Using Recursion

    /**
     * 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)
                return result;
            result.add(root.val);
            if(root.left != null)
                result.addAll(preorderTraversal(root.left));
            if(root.right != null)
                result.addAll(preorderTraversal(root.right));
            return result;
        }
    }

    DP

    public ArrayList<Integer> preorderTraversal(TreeNode root) {
            ArrayList<Integer> result = new ArrayList<Integer>();
            
            preorder(root, result);
            
            return result;
        }
        
        public void preorder(TreeNode root, ArrayList<Integer> result){
            if(root != null){
                result.add(root.val);
                preorder(root.left, result);
                preorder(root.right, result);
            }
        }
  • 相关阅读:
    Different ways how to escape an XML string in C# (zz)
    sql server 中nvarchar(max)性能
    使用 access 的一些限制条件 (zz)
    js 常用属性和方法
    js 常用关键字及方法
    <推荐>35个优秀的电子商务网站界面 (转)
    ASP.NET底层架构 22
    JSON 学习总结(1)
    学习记录
    asp.net原理(总结整理 2)
  • 原文地址:https://www.cnblogs.com/RazerLu/p/3552865.html
Copyright © 2011-2022 走看看