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 }
  • 相关阅读:
    模板库
    LCT小结
    BZOJ1502: [NOI2005]月下柠檬树
    技术资料分享
    ORM介紹及ORM優點、缺點
    依賴注入入門——Unity(二)
    面向切面編程入門(一)
    依賴注入入門——Unity(一)
    WCF、.Net Remoting、Web Service概念及区别
    深入设计模式(四)——建造者模式
  • 原文地址:https://www.cnblogs.com/huntfor/p/3947945.html
Copyright © 2011-2022 走看看