Recursion in Java


  • 0
    A
    public class Solution {
        public String tree2str(TreeNode t) {
            // algorithm 2017/06/04: recursion is the way to go
            String result = null;
            if (null == t) {
                result = "";
            } else if (null == t.left && null == t.right) {
                result = t.val + "";
            } else if (null != t.left && null == t.right) {
                result = t.val + "(" + tree2str(t.left) + ")";
            } else if (null == t.left && null != t.right) {
                result = t.val + "()" + "(" + tree2str(t.right) + ")";
            } else {
                result = t.val + "(" + tree2str(t.left) + ")" + "(" + tree2str(t.right) + ")";
            }
            return result;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.