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);
            }
        }
  • 相关阅读:
    数组常用操作实现
    链表简单实现栈与队列
    亿万级别的表数据处理方式
    ubuntu安装与卸载.dep软件
    pg数据库表接口和数据导出
    深入分析理解Tomcat体系结构
    Servlet源码级别进行详解
    Maven命令行创建java或javaWeb项目
    解释语言与编译语言
    C++中Reference与Pointer的不同
  • 原文地址:https://www.cnblogs.com/RazerLu/p/3552865.html
Copyright © 2011-2022 走看看