二叉树路径的最大值

Given a binary tree, find the maximum path sum.

For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.

For example:
Given the below binary tree,

       1
      / \
     2   3

Return 6.

这种题目和我们以前做的求从头结点到达二叉树的最下面一层节点的路径求和差不多,只不过现在求在这颗树里面任意的路径最大值.

我们先建立求和的思路

树里面的一条路径是什么呢?
从root节点向两边延伸,每次蔓延到的节点,又有两种选择,左,右,在蔓延的过程中一直记录着cur节点+两边蔓延路径的最大值,

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    private int max;
    public int maxPathSum(TreeNode root) {
        if (root == null) {
            return 0;
        }
        max = Integer.MIN_VALUE;
        countRound(root);
        return max;
    }
    // 这个函数只是计算 在node节点往两边延伸的 一条路径的最大值
    public int countRound(TreeNode node) {
        if (node == null) {
            return 0;
        }
        // 如果左子树里面的最大路径负数,不计算
        int left = Math.max(0,countRound(node.left));
        // 如果右子树里面的最大路径负数,不计算
        int right = Math.max(0, countRound(node.right));
        max = Math.max(max, (left + right) + node.val);
        return Math.max(left, right) + node.val;
    }
}

Given a binary tree, return the inorder traversal of its nodes’ values.

Example:

Input: [1,null,2,3]
   1
    \
     2
    /
   3

Output: [1,3,2]
我们很容易想到树的递归便利,但是非递归的代码我们还是需要会写的.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        //if (root != null)
        List<Integer> res = new ArrayList<>();
        // 我们可以使用栈来完成这件事情
        Stack<TreeNode> stack = new Stack<>();
        TreeNode p = root;
        while (p != null || !stack.isEmpty()) {
            // 中序遍历优先访问 左孩子节点
            while (p != null) {
                stack.push(p);
                p = p.left;
            }
            if (!stack.isEmpty()) {
                p = stack.pop(); // 出栈元素 为最左节点
                res.add(p.val);
                p = p.right;
            }
        }
        return res;
    }
}

递归C++

void inOrder(BinTree *root){  
    if(root!=NULL){  
        inOrder(root->lchild);  
        cout<<root->dada<<" ";  
        inOrder(order->rchild);  
    }  
}  

猜你喜欢

转载自blog.csdn.net/qq_33797928/article/details/80001056
今日推荐