概述:

左耳朵耗子专栏《左耳听风》 用户自发每周完成一个ARTS:

1.Algorithm:每周至少做一个 leetcode 的算法题

2.Review:阅读并点评至少一篇英文技术文章

3.Tip:学习至少一个技术技巧

4.Share:分享一篇有观点和思考的技术文章

 

Algorithm
题目概述:

 

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

For example:
Given binary tree{1,#,2,3},

   1
    \
     2
    /
   3

 

return[3,2,1].

 

思路分析:

这道题比较简单,可以通过递归的方式来实现后序遍历:

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
import java.util.ArrayList;
public class Solution {
    
    
     ArrayList<Integer> list = new ArrayList<>();

    
    public ArrayList<Integer> postorderTraversal(TreeNode root) {
        postHandleNode( root);
        return list;
    }
    
    
    public void postHandleNode(TreeNode root){
        if(root==null){
            return ;
        }
        postHandleNode(root.left);
        postHandleNode(root.right);
        saveNode(root);
    }

    public void saveNode(TreeNode root){
        list.add(root.val);
    }
    
   
}

 

前序遍历

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].

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
import java.util.ArrayList;
public class Solution {
     ArrayList<Integer> list = new ArrayList<>();
    
    public ArrayList<Integer> preorderTraversal(TreeNode root) {
         preorderHandel(root);
        return list;
    }
    
        public void preorderHandel(TreeNode root) {
        if (root == null) {
            return;
        }
        saveNode(root);
        preorderHandel(root.left);
        preorderHandel(root.right);
        
    }



    public void saveNode(TreeNode root) {
        list.add(root.val);
    }

}

 

 

 

 

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐