美文网首页
【1错-1】Construct String from Bina

【1错-1】Construct String from Bina

作者: 7ccc099f4608 | 来源:发表于2019-01-20 00:04 被阅读0次

    https://leetcode.com/problems/construct-string-from-binary-tree/

    日期 是否一次通过 comment
    2019-01-20 02:38 对何时加()理解不够清楚
    image.png image.png

    (来源:https://leetcode.com/problems/construct-string-from-binary-tree/

    1. 非递归:TODO;
    2. 递归:preOrder,处理好何时加上()

    1. 非递归

    
    

    2.递归

    class Solution {
        public String tree2str(TreeNode t) {
            if(t == null) {
                return "";
            }
            
            StringBuilder sb = new StringBuilder();
            helper(t, sb);
            return sb.toString();
        }
        
        private void helper(TreeNode t, StringBuilder sb) {
            if(t == null) {
                return;
            }
            sb.append(t.val);
            if(t.left != null || t.right != null) {
                sb.append("(");
                helper(t.left, sb);
                sb.append(")");
                
                if(t.right != null) {
                    sb.append("(");
                    helper(t.right, sb);
                    sb.append(")");
                }
            }
            
        }
    }

    相关文章

      网友评论

          本文标题:【1错-1】Construct String from Bina

          本文链接:https://www.haomeiwen.com/subject/woptjqtx.html