樹的前中後序

前序就是根左右,中序就是左根右,後序就是左右根

樹結構

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */

中序

void in(List<Integer> list,TreeNode root){
        if(root == null)return;
        in(list,root.left);
        list.add(root.val);
        in(list,root.right);
    }

前序

void pre(List<Integer> list,TreeNode root){
        if(root == null)return;
        list.add(root.val);
        pre(list,root.left);
        pre(list,root.right);
    }

後序

void post(List<Integer> list,TreeNode root){
        if(root == null)return;
        post(list,root.left);
        post(list,root.right);
        list.add(root.val);
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章