美文网首页
leetcode:树(easy)

leetcode:树(easy)

作者: crazydane | 来源:发表于2017-05-31 14:53 被阅读0次

    leetCode: 112. Path Sum

    Problem

    Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

    For example:
    Given the below binary tree and sum = 22,

                  5
                 / \
                4   8
               /   / \
              11  13  4
             /  \      \
            7    2      1
    

    return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

    解题思路:

    采用递归的思想,(root->sum) 意味着 (root.left->sum - root.value || root.right->sum - root.value)
    如果当前节点为null则返回false,如果当前节点为叶子节点则判断该节点值是不是等于sum,否则递归。

    代码如下:
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public boolean hasPathSum(TreeNode root, int sum) {
            if(root == null) return false;
            if(root.left==null&&root.right==null&&root.val==sum){
                return true;
            }
            return(hasPathSum(root.right,sum-root.val)||hasPathSum(root.left,sum-root.val));
        }
    }
    

    LeetCode 226 Invert Binary Tree

    Problem:

    Invert a binary tree.

         4
       /   \
      2     7
     / \   / \
    1   3 6   9
    

    to

         4
       /   \
      7     2
     / \   / \
    9   6 3   1
    

    Trivia:This problem was inspired by this original tweet by Max Howell:Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so fuck off.

    解题思路:

    还是用递归的思想。

    代码如下:
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public TreeNode invertTree(TreeNode root) {
            if(root==null){
                return null;
            }
            if(root.left==null&&root.right==null){
                return root;
            }
            root.left = invertTree(root.left);
            root.right = invertTree(root.right);
            
            TreeNode temp = root.left;
            root.left = root.right;
            root.right = temp;
            return root;
        }
    }
    

    相关文章

      网友评论

          本文标题:leetcode:树(easy)

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