[leetcode]binary-tree-postorder-traversal

1767 단어
문제: 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]. 두 갈래 나무의 뒷부분이 두루 다니는데, 내가 리코드에서 풀었던 가장 간단한 문제다.해법 1: 귀속
import java.util.*;
/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ArrayList postorderTraversal(TreeNode root) {
        ArrayLista=new ArrayList();
        if (root==null)
            return a;
        a.addAll(postorderTraversal(root.left));
        a.addAll(postorderTraversal(root.right));
        a.add(root.val);
        return a;
    }
}

해법2:교체
import java.util.*;
/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ArrayList postorderTraversal(TreeNode root) {
         ArrayLista=new ArrayList();
        if (root==null)
            return a;
        Stackstack1=new Stack();
        Stackstack2=new Stack();
        stack1.add(root);
        while (!stack1.empty())
        {
            TreeNode t=stack1.pop();
            if (t.left!=null)
                stack1.add(t.left);
            if (t.right!=null)
                stack1.add(t.right);
            stack2.add(t);
        }
        while (!stack2.empty())
        {
            a.add(stack2.pop().val);
        }
       return a;
    }
}

좋은 웹페이지 즐겨찾기