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

    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?

    算法思路:

    思路1:递归版

    代码如下:

     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     List<Integer> res = new ArrayList<Integer>();
    12     public List<Integer> preorderTraversal(TreeNode root) {
    13         if(root == null) return res;
    14         res.add(root.val);
    15         if(root.left != null) preorderTraversal(root.left);
    16         if(root.right != null) preorderTraversal(root.right);
    17         return res;
    18     }
    19 }

    2. 非递归实现:

    借助栈,每一次弹栈处理栈顶元素之后都将右节点、左节点分别压栈,大家画个图就明白了

    代码如下:

     1 public class Solution {
     2     public List<Integer> preorderTraversal(TreeNode root) {
     3         List<Integer> res = new ArrayList<Integer>();
     4         if(root == null) return res;
     5         Stack<TreeNode> stack = new Stack<TreeNode>();
     6         stack.push(root);
     7         while(!stack.isEmpty()){
     8             TreeNode node = stack.pop();
     9             res.add(node.val);
    10             if(node.right != null){
    11                 stack.push(node.right);
    12             }
    13             if(node.left != null){
    14                 stack.push(node.left);
    15             }
    16         }
    17         return res;
    18     }
    19 }
  • 相关阅读:
    如何进行有效沟通避免出现误会
    如何进行有效沟通
    怎样提高自己的团队合作能力
    javaScript简介
    css文本格式详解
    css简介及相关概念
    WebGL10---3D模型的加载与使用
    Canvas绘图与动画详解
    Canvas绘制时钟
    WebGL9----将canvas作为纹理,将动画作为纹理(2)
  • 原文地址:https://www.cnblogs.com/huntfor/p/3947945.html
Copyright © 2011-2022 走看看