zoukankan      html  css  js  c++  java
  • 二叉树的前序遍历

    题目描述:

    Given a binary tree, return the preorder traversal of its nodes' values.

    思路:上一题用的是栈,和列表头插法,这一题用的是栈和列表尾插法

    /**
     * Definition for binary tree
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    import java.util.*;
    public class Solution {
        public ArrayList<Integer> preorderTraversal(TreeNode root) {
            ArrayList<Integer> list = new ArrayList<Integer>();
            if(root == null)
                return list;
            Stack<TreeNode> stack = new Stack<TreeNode>();
            stack.push(root);
            while(!stack.isEmpty()){
                TreeNode temp = stack.pop();
                list.add(temp.val);
                if(temp.right != null)
                    stack.push(temp.right);
                if(temp.left != null)
                    stack.push(temp.left);
            }
            return list;
        }
    }
  • 相关阅读:
    CSS 选择器
    HTML lable和fieldset
    html image和表格
    HTML a标签
    html 提交后台的标签
    HTML INPUT系列使用
    HTML内标签、换行
    HTML 头部详解
    单例模式
    const 指针的三种使用方式
  • 原文地址:https://www.cnblogs.com/whu-2017/p/9716841.html
Copyright © 2011-2022 走看看