• 树——binary-tree-postorder-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].

    递归方法:

     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 import java.util.*;
    11 public class Solution {
    12     public ArrayList<Integer> preorderTraversal(TreeNode root) {
    13         ArrayList<Integer> list = new ArrayList<Integer>();
    14         if(root==null)
    15             return list;
    16         preorderTraversal(root, list);
    17         return list;
    18     }
    19     public void preorderTraversal(TreeNode root, ArrayList<Integer> list){
    20         if(root==null)
    21             return;
    22         list.add(root.val);      //先遍历根节点
    23         preorderTraversal(root.left, list);    //其次遍历左节点
    24         preorderTraversal(root.right, list);    //最后遍历右节点
    25     }
    26 }

    非递归方法(利用栈)

      说明,按照“右 - 左 - 根”的顺序进栈,“根 - 左 - 右”的顺序出栈,所有为先序遍历

     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 import java.util.*;
    11 public class Solution {
    12     public ArrayList<Integer> preorderTraversal(TreeNode root) {
    13          ArrayList<Integer> list = new ArrayList<Integer>();
    14         if(root==null)
    15             return list;
    16         Stack<TreeNode> stack = new Stack<TreeNode>();
    17         stack.push(root);
    18         while(!stack.isEmpty()){
    19             TreeNode node = stack.pop();
    20             list.add(node.val);
    21             if(node.right!=null)
    22                 stack.push(node.right);
    23             if(node.left!=null)
    24                 stack.push(node.left);
    25         }
    26         return list;
    27     }
    28 }
  • 相关阅读:
    二进制运算基础
    初识Tomcat系统架构
    MySQL InnoDB引擎锁的总结
    Java并发编程:并发容器之CopyOnWriteArrayList
    java类的加载机制
    Nginx实现tomcat集群进行负载均衡
    Java序列化对象为字符串并将字符串反序列化为对象
    数据库的四大特性及事务的隔离级别
    人性的弱点
    华为工作法摘抄笔记
  • 原文地址:https://www.cnblogs.com/jiqianqian/p/7387987.html
Copyright © 2020-2023  润新知