1. 程式人生 > 實用技巧 >CodeForces-232B Table 組合數學 DP

CodeForces-232B Table 組合數學 DP

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

1.遞迴

class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        inorder(root,res);
        return res;
    }

    public void inorder(TreeNode root,List<Integer> res){
        if(root ==null)
            return ;
        inorder(root.left,res);
        res.add(root.val);
        inorder(root.right,res);

    }
}

2.迭代

class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        Stack<TreeNode> st = new Stack<TreeNode>();

        while(st.size()>0||root!=null){
            if(root!=null){
                st.add(root);
                root=root.left;
            }else{
                TreeNode temp = st.pop();
                res.add(temp.val);
                root=temp.right;
            }
        }
        return res;
    }
}